React State - What? Why? When?

What is State

  • It is just an instance of the React Component Class

  • It is an object with set of observable properties that control the behaviour of the component

  • It holds some information that may change over the life time of the component

But if you have gone through props you would wonder what's the difference between state and props? They do have some differences....

Props vs State:

  • Props are immutable, once set cannot be changed. State hold data that can change from time to time.
  • Props can be used anywhere. State are used only Class Component (Can be used in functional class too using hook)

  • Props are set by parent component. State are updated with event handlers.

State Properties:

Here are some tips to keep in mind while using state.

  • The initial state is defined in the constructor of the component's class
Class MyState extends React.Component
{
   constructor(props)
      {
          super(props);
          this.state={attribute:"Value"};
      }
}
  • State should not be updated Explicitly. It can be explicitly done in the constructor while initializing the state but when updating. It will not be able to detect and re-render the changes made. setState() method is used to update the state.
this.setState({attribute: "new-value"});
  • React uses Asynchronous state updates, meaning takes multiple setState method and update all of them in a single go. So when you think about it using the current state may not be a good idea.

Wrong Method :(

this.setState({counter:this.state.count + this.props.diff});

Right Method :)

this.setState((prevState,props)=>
({counter:prevState.count + props.diff}));

From the above code you will notice that setState method has 2 arguments. The first argument carries the updater function and the second argument has the props. Passing an updater function allows you to access the current state inside the updater. Since setState is batched, lets you chain updates and build on top of each other instead of conflicting.

Now the next question arises is why is setState Asynchronous?....why cant you update the state immediately when called?.....

The answer would be say if both Parent and Child call setState, as we know when parent re-renders its child elements are also rendered which results in double re-rendering. So thats why react waits untill all components call setState in the event handler before starting to re-render. This helps to boost performance and avoid unnecessary re-renders.

State Hook

Say you were writing a function component and then you realize you need to add some state. Now it will be a waste of time to convert everything into class component, instead you can use hook to add state into the component.

About Hook:

  • They are a new addition in React

  • They let you use state and other React features without writing a class

  • They are obtained by importing useState Hook from React.

Declaring State Variable: In class component we usually initialize the state as this.state.

class Example extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      count: 0
    };
  }

But in function component that's not possible. So instead instead we can call useState hook directly into our component.

import React, { useState } from 'react';

function Example() {
  const [count, setCount] = useState(0);
}

Here useState declares the state variable. As we no after the function returns all the variables within the function disappears but the state variable will be preserved by react.

The useState will have the initial state as its argument. This state can be an object, string, numbers.....

The useState Returns a pair of values, the current state and the function that updates it. As you can see in the above code the useState returns in the form of an array. This array in JavaScript is called as "array destructing"

Updating State

For Class Component for updating the state we used setState.

<button onClick={()=>this.setState({count:this.state.count+1})}>Click me</button>

But for Function component, we already have setCount.

<button onClick={()=>setCount(count+1)}>Click me</button>

Here the in function component the state is replaced and not merged like in this.state

Conclusion

So here's a recap about state they are instances of the class which controls the behaviour of the class with its properties. These properties within the states may change based on the events encountered which may change the behaviour of the component.