States

We can use regular variables in React however there’s a problem with storing vital data in regular variables as this data can be lost between re-renders; therefore we need to store vital data in a way that the data is not lost between re-renders.

This is where states come into play. States are special kinds of storage spaces that store the data and this data cannot be lost between re-renders. States created using the useState hook can be set only using their corresponding state setters. In class-based components, the state can only be set using this.setState function.

States will hold the data from the mounting of the component till the component unmounts or in other words, the state of a component will be maintained throughout the component’s life cycle.

State updates are asynchronous and not immediate. Each state update makes one rerender. So n times states are updated then n times rerenders will occur. After React v18 all the state updates are batched together to make sure fewer rerenders happen.

  • Read more about states here.