Difference Between State and Props in React

Difference Between State and Props in React

In this tutorial, we are going to learn about what is the difference between state and props in react with the help of examples.

State

  • In react state helps us to store the component-specific data, the data we stored in the state is private.
  • State is mutatable in react.
  • The only way to update the state in react is by using this.setState() method.
  • State updates will re-render your component with the updated changes.

Let’s see an example.

import React, { Component } from "react";

class Counter extends Component {
  // state is initialzed with count value 0
  state = {
    count: 0
  };

  handleIncrement = () => {
    //updating count value
    this.setState({
      count: this.state.count + 1
    });
  };

  render() {
    return (
      <div>
        <h1>{count}</h1>
        <button onClick={handleIncrement}>Increment</button>
      </div>
    );
  }
}

export default Counter;

Props

  • Props are used to pass the parent component (state) data to the child components, it means by using props we are communicating with the child components.
  • Props are read-only in react.

Let’s see an example.

import React, { Component } from "react";
import Welcome from "./Welcome";

class App extends Component {
  state = {
    msg: "Welcome to react"
  };

  render() {
    return (
      <div>
        <h1>Learning react</h1>
        // passing message prop to the Welcome component
        <Welcome messsage={this.state.msg} />      </div>
    );
  }
}

export default App;

In the above code, we passed the message prop to <Welcome> component.

Now, inside the Welcome component we can access the message prop using this.props.

Welcome.js
import React, { Component } from "react";

class Welcome extends Component {

  render() {
      console.log(this.props.message); //Welcome to react
    return (
        <h1>{this.props.message}</h1>    );
  }

}

Inside child components, we can’t change the props.

Conclusion

The state is used to the store the data in the central components, by using props we are passing state down to the child components instead of creating a state in every component.