How to update object using setState in React

Suppose we have a React component as shown below

  
    class ShoppingList extends React.Component{
      state = {
        site: {
          name: "Instagram",
          link: "https://instagram.com",
          text: 'abc'
        },
        description: 'List of sites for shopping'
      }
      render(){
        ...
      }
    }
  

Now we want to update the state variable site with different name and link of site, and keep the other state as before.

  
    state = {
      site: {
        name: "Techdomain",
        link: "https://techdoma.in",
        text: 'abc'
      },
      description: 'List of sites for shopping'
    }
  

There are multiple ways to update the object in a state variable using setState method in React

Passing a function to the setState function

setState function allows a callback function which provides previous state. We can use the spread operator and merge the new state with previous state.

  
    this.setState(prevState=>{
      const { site } = prevState;
      return {
        site: {
          ...site,
          name: "Techdomain",
          link: "https://techdoma.in"
        }
      }
    })
  

Passing object directly to setState function

In this case we do not use prevState callback function, and directly merge the new state value with the current state value of site

  
    this.setState({
      site: {
        ...this.state.site,
        name: "Techdomain",
        link: "https://techdoma.in"
      }
    })
  

What is difference between above two approach?

Passing an update function allows you to access the current state value inside the updater. Since setState calls are batched, this lets you chain updates and ensure they build on top of each other instead of conflicting.

setState updates asynchronously. It updates in batches to improve the performance of React app. In order to understand more, click here to read more on difference between passing function and passing object to setState

Difference between passing function and object to setState function

State update is done asynchronously in React. So it is important to understand the difference between passing function or object to setState function.