How is state different than props in React?

Experience Level: Junior
Tags: React

Answer

In React, both state and props are used to manage data in a component. However, they differ in their functionality and usage.

Props are short for properties, and they are used to pass data from a parent component to a child component. They are immutable, meaning that they cannot be changed within the child component. Props are passed down as an argument to the child component and can be accessed using the 'this.props' syntax. Props are useful when we want to reuse a component with different data. For example, if we have a 'Person' component, we can pass different names and ages as props to create different instances of the component.

State, on the other hand, is used to manage data within a component. It is mutable, meaning that it can be changed within the component. State is initialized within the constructor of a component and can be accessed using the 'this.state' syntax. State is useful when we want to update the data within a component based on user interactions or other events. For example, if we have a 'Counter' component, we can use state to keep track of the current count and update it when the user clicks a button.


// Example of using props and state in a component

class Person extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      age: this.props.age
    };
  }

  handleClick = () => {
    this.setState({ age: this.state.age + 1 });
  }

  render() {
    return (
      <div>
        <p>Name: {this.props.name}</p>
        <p>Age: {this.state.age}</p>
        <button onClick={this.handleClick}>Increase Age</button>
      </div>
    );
  }
}

// Usage of the Person component with different props

<Person name="John" age={25} />
<Person name="Jane" age={30} />
React for beginners
React for beginners

Are you learning React ? Try our test we designed to help you progress faster.

Test yourself