What is the difference between React component instance property and state property?
state
and instance properties
serve different purposes. While calling setState with empty arguments will cause a render and will reflect the updated instance properties, state can be used for many more features like
comparing prevState
and currentState
in shouldComponentUpdate to decide whether you want to render or not, or in lifecycle method like componentDidUpdate where you can take an action based on state change.
state is a special instance property used by react to serve special purposes. Also in setState
, state updates are batched for performance reasons and state updates happen asynchronously unlike class variable updates which happen synchronously. A class variable won't have these features.
Also when you supply a class variable as prop to the component, a change in this class variable can't be differentiated in the lifecycle methods of the child component unless you are creating a new instance of the variable yourself. React does it with state
property for you already.
Both have different purpose. Rule of thumb is:
- Use
state
to store data if it is involved in rendering or data flow (i.e. if its used directly or indirectly in render method) - Use
other instance fields
to store data if value is NOT involved in rendering or data flow (to prevent rendering on change of data) e.g. to store a timer ID that is not used in render method. See TimerID example in official docs to understand this valid case.
If some value isn’t used for rendering or data flow (for example, a timer ID), you don’t have to put it in the state. Such values can be defined as fields on the component instance.
Reference: https://reactjs.org/docs/react-component.html#state