What is state in React

No !!! we are not talking about state of matter but yeah the analogy is same in React.

State is an instance of React Component. State of a component is an object that holds some information that may change over the lifetime of the component. The state object is where you store property values that belongs to the component. When state object changes, the component re-renders.

State simply is a property of the component class, unlike props you have to call it state though, the name is not optional. You can then access it via this.state in your class JSX code(which you return in the required render() mehtod). Whenever the state changes, the component will re-render and reflect the new state. The difference to props is, that this happens within one and the same component –  you don’t receive new data(props) from outside.

Difference Between props and state

Only the class based components can define and use state, but props don’t have this limitation. Once set the props cannot be changed while state is an observable object that is to be used to hold data that may change over time and to control the behavior after each change. While props are set by the parent component, state is update by even handlers.

The example below shows how we can use props to transfer data in state.

We can access props like we did before in the last post

Conclusion

  • The state object is where you store property values that belongs to the component.
  • When state object changes, the component re-renders.
  • The state object can contain as many properties as you like.
  • state allows you to create components that are dynamic and interactive. The hear of every React component is its state.
  • state determines how its component renders and behaves.