state vs props in react

Posted on Apr 29, 2020

In React, components are used to translate raw data into rich HTML. Props and state constitute the raw data that gets transformed into HTML using the render() function of a component.

State belongs to a particular component, is stored within the component, and is used only by the component itself. State can be updated within a component, for instance based on an action (such as user event or network response). By default a component will not have state, so to add an initial state to a component, you can add a class constructor to a class component. The following is an example of using a List Component and constructor method to set the initial state of a count key to a value of 0:

class List from React.Component {

   constructor(props) {
    super(props);
    this.state = {count: 0 };
  }

  onClick() {
    this.setState({count: this.state.count + 1});
  }

  render() {
    return (
      <div>
        <div>count:{this.state.count}</div>
        <button onClick={this.onClick}>add to list</button>
      </div>
    );
  }
};
ReactDOM.render(<List />, document.getElementById("root"));

When the button is clicked once, the state value will change to 1 using the setState() method and re-render the component with the updated value.

Props is short for properties and is a plain Javascript object. In a component, props are values, they can be hardcoded or if they are set in a parent component they can only be changed by a parent component. In other words, a component receives props from its parent and at this point the props cannot change. That child component can continue to pass props down to its own children. The following is an example of where a name prop is called in a child Welcome component. The prop is set using JSX in a parent App component. Props are accessible from a class component by calling on the class using this.props:

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

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

ReactDOM.render(<App />, document.getElementById('root'));

In a functional component, props are called like a Javascript function argument:

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

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

When do we want to use props?

When you want to access data from parent components in a child component, you pass down data using props.

When do we want to use state?

When you want to change data within a component.