Skip to content Skip to sidebar Skip to footer

What Difference Between Direct Argument And Callback In Setstate?

What difference between direct argument and callback in setState? I've heard that the react scheduler only correctly exposes component updates when a callback is used. So that they

Solution 1:

Using the callback form allows you to use the previous value in state, even if the previous value hasn't been rendered yet. For example:

const [counter, setCounter] = useState(0);

constsomeHandler = () => {
  setCounter(counter + 1);
  setCounter(counter + 1);
}

will only end up increasing counter by one, because the counter that's in scope when the handler runs is from a single render. It's like doing setCounter(1); setCounter(1), so counter ends up being 1, not 2.

Using the callback form allows you to use the previous state:

setCounter(counter => counter + 1);
setCounter(counter => counter + 1);

will properly increase counter by 2, not just 1.

Another difference is that using the callback form allows you to put functions into state:

const [fn, setFn] = useState();
constfnToPutInState = () => {
  console.log('fn');
};

// ...setFn(fnToPutInState);

will result in the function being invoked immediately, rather than setting state. The solution is to return the function from a callback instead:

setFn(() => fnToPutInState);

Post a Comment for "What Difference Between Direct Argument And Callback In Setstate?"