When to use an object in `setState` instead of using functional `setState`?

Asked
Active3 hr before
Viewed126 times

7 Answers

insteadobjectusing
90%

The norm is to use an object, it's also less code and easier to read. The only reason u want to use a function setState is when u need to access the previous state.,a function being passed as the argument to setState and ,Is there a significant reason why we should use an object in setState in normal cases vs using it as a function?

consider the following example

// you have a switch state

state = {
   checked: false
}

// .. and later in an onChange method 

onChange = () => {
      const {
         checked
      } = this.state;
      // this is problematic because react works in an async fashion, so it could be that when this function was called checked was false, however it was only executed later when checked was actually true 
      this.setState({
            checked: !checked
         }

         // on the other hand  this form is safe, even if things were happening async, you are safe because you act on the most updated state 
         this.setState(prvState => {
            ...prvState,
            checked: !prvState.checked
         })
      }
88%

If you know you’re going to use setState to update your component and you know you’re going to need the current state or the current props of your component to calculate the next state, passing in a function as the first parameter of this.setState instead of an object is the recommended solution.,But, often there is a need to update our component’s state using the current state of the component. Directly accessing this.state to update our component is not a reliable way to update our component’s next state. From the React documentation:,Because this.props and this.state may be updated asynchronously, you should not rely on their values for calculating the next state.

The component for the feedback page has a showForm boolean which determines whether the form or the thank you message should display. The initial state of my feedback form component looks like this:

this.state = {
   showForm: true
}
load more v
72%

Remember how we said setState() works? Well, what if I told you that instead of passing an object, you could pass a function?,First, “multiple setState() calls” could mean calling setState() inside a single function more than once, like this:,Again, I think seeing some code would be great. This time though, we’re gonna fake everything. Know that this is not the real thing, but is instead just here to give you an idea of what React is doing.

Pretag
 Pretag team - issue, fix, solve, resolve
65%

Pass a function instead of an object to setState to ensure the call always uses the most updated version of state (see below). ,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:,Calls to setState are asynchronous - don’t rely on this.state to reflect the new value immediately after calling setState. Pass an updater function instead of an object if you need to compute values based on the current state (see below for details).

incrementCount() {
   // Note: this will *not* work as intended.
   this.setState({
      count: this.state.count + 1
   });
}

handleSomething() {
   // Let's say `this.state.count` starts at 0.
   this.incrementCount();
   this.incrementCount();
   this.incrementCount();
   // When React re-renders the component, `this.state.count` will be 1, but you expected 3.

   // This is because `incrementCount()` function above reads from `this.state.count`,
   // but React doesn't update `this.state.count` until the component is re-rendered.
   // So `incrementCount()` ends up reading `this.state.count` as 0 every time, and sets it to 1.

   // The fix is described below!
}
load more v
75%

Pretag
 Pretag team - issue, fix, solve, resolve
40%

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. , Because setState is asynchronous, if you update state multiple times by passing object to setState, then the updates will be missed. , 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

Lets take an example where we pass object to setState function.

  
    class Example extends React.Component{
      state = {
        no: 0
      }
      componentDidMount(){
        this.incrementNo();
        this.incrementNo();
        this.incrementNo();
      }
      incrementNo(){
        this.setState({
          no: this.state.no + 1
        })
      }
      render(){
        return <div>Value of no: this.state.no</div>;
      }
    }
  
load more v
22%

If you’ve explored the useState Hook in React before, you may have noticed something different about the setState function above…,How to create a new Context in React using React.createContext.,You create a Context object in React by using React.CreateContext, and then passing in an initial value, like so:

import AppContext from './appContext.js';

class Example extends React.Component {
   static context = AppContext;
   render() {
      let value = this.context;
      ...
   }
}
load more v

Other "instead-object" queries related to "When to use an object in `setState` instead of using functional `setState`?"