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
});
}
//...
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);
}
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?
Top comments (2)
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.
useCallback