Is it a bad design to remove the setState callback?
official_dulin

official_dulin @mrdulin

About: I'm Full Stack Developer, Electrical Engineer and Perfectionist.

Location:
Shanghai
Joined:
Sep 2, 2018

Is it a bad design to remove the setState callback?

Publish Date: Aug 4 '22
2 2

When we use React class component, there is a instance method setState(updater[, callback])

setState callback which is guaranteed to fire after the update has been applied.

However, when we use the setState method returned by useState() hook, it has no callback anymore.

Let's compare setState(updater[, callback]) and the setState returns by useState() hook.

// We can see all the logic at a glance
const onIncreaseButtonClick = () => {
  // step 1. Updating the state
  const nextState = {};
  this.setState(nextState, () => {
    // step 2. call API
  });
}
//...
Enter fullscreen mode Exit fullscreen mode
const [state, setState] = useState();
useEffect(() => {
  // step 2. call API
}, [state]);

// We need to scroll the editor to the top to see the second part of the logic
// 200 lines code
// ...
// ...

const onIncreaseButtonClick = () => {
  // step 1. Updating the state
  const nextState = {};
  setState(nextState);
}
Enter fullscreen mode Exit fullscreen mode

Do you see the difference?

When the button click event occurs, we have two parts of logic: update state and call API.

In the former case, the two parts of the logic code are organized together, and the execution order and code writing order are the same.

In the latter case, the two parts of the logic are split in different places, the logic for updating the state is in the event handler and the logic for the call API is placed in useEffect(). And the order of execution and the order of reading (writing) is not the same.

Some people have the same view as me, such as https://stackoverflow.com/questions/54954091/how-to-use-callback-with-usestate-hook-in-react

That's why someone implements a useStateCallback hook.

What do you think?

Comments 2 total

  • Ivan Jeremic
    Ivan JeremicAug 4, 2022

    useCallback

  • CFV
    CFVAug 30, 2024

    Literally just have a hook encapsulating this logic instead of grafting hundreds of lines of random state management stuff into your component.
    It’s easier to maintain later.

Add comment