Corporate Training
Request Demo
Click me
Menu
Let's Talk
Request Demo

Tutorials

State and Props

State and Props in React.js

State and props are two fundamental concepts in React.js that allow you to manage and pass data within your components. They play crucial roles in creating dynamic and interactive user interfaces. Let's explore the concepts of state and props in React:

State:

1. Component State:

  • State is a JavaScript object that represents the dynamic data of a component.
  • It is used to store and manage data that can change over time within a component.
  • State is initialized in the constructor of a class component and can be updated using the setState method.

Example (Class Component):

class Counter extends React.Component {
  constructor(props) {
    super(props);
    this.state = { count: 0 };
  }

  increment = () => {
    this.setState({ count: this.state.count + 1 });
  };

  render() {
    return (
      

Count: {this.state.count}

); } }      

 

 

2. Updating State:

  • You should not directly modify the state; instead, use setState to update it.
  • React may batch multiple setState calls for performance reasons, so you should use the functional form of setState when the new state depends on the previous state.

Example:

// Incorrect
this.state.count = this.state.count + 1; // Do not do this

// Correct
this.setState((prevState) => ({ count: prevState.count + 1 }));
       

 

 

Props:

1. Component Props:

  • Props (short for properties) are a way to pass data from a parent component to a child component.
  • Props are read-only and help make your components reusable and configurable.
  • Props are passed as attributes to a component in JSX.

Example:

function Welcome(props) {
  return <h1>Hello, {props.name}</h1>;
}

const element = <Welcome name="Alice" />;
     

 

2. Default Props:

  • You can define default values for props using defaultProps in a functional or class component.

Example (Functional Component):

     function Welcome(props) {
  return <h1>Hello, {props.name}</h1>;
}

Welcome.defaultProps = {
  name: "Guest",
};
 

 

Example (Class Component):

class Welcome extends React.Component {
  render() {
    return <h1>Hello, {this.props.name}</h1>;
  }
}

Welcome.defaultProps = {
  name: "Guest",
};
 

 

3. Passing Props:

  • To pass props to a child component, include them as attributes in the JSX element.

Example:

function App() {
  return (
    <div>
      <Welcome name="Alice" />
      <Welcome name="Bob" />
    </div>
  );
}
     

 

In summary, state allows you to manage dynamic data within a component, while props enable data flow from parent to child components. Understanding when to use state and when to use props is essential for building React applications that are both interactive and modular.