In the syntax
const [state, setState] = useState(0);
I will call variable in state
position as state variable <name_of_variable> (for example, the state variable count
)
I will call function in setState
position as state-update function <name_of_function> (for example, the state-update function setCount
)
I will call value in 0
position as initial value of state <name_of_state> (for example, the initial value of state count
)
State batching is a React behavior where multiple state-update functions are batched together and run all at once instead of run one by one. Let's take a look at the code below
const App = () => { const [a, setA] = useState(0); const [b, setB] = useState("hello"); useEffect(() => { console.log("State change"); }); const handleClick = () => { setA(a + 1); setB(b + "new hello"); }; return ( <div> {a} --- {b} <button onClick={handleClick}>Change state</button> </div> ); };
Try to run the code above and click on the button. Can you guess how many time you will see the message State change
in the console?
The answer is 1 log message per button click. When I first learned React I did the wrong guess, which is 2 log messages per button click. Our guess of 2 logs is wrong. But why is it? Let analyze why we came up with such guess and what actually happened.
This is what will happen according to our expectation:
handleClick
is calledsetA
setA
run change the value of state variable a
a
change, the callback in useEffect
is calledsetB
runsetB
run change the value of state variable b
b
change, the callback in useEffect
is called---> In short, we will have two re-render and two run of useEffect
callback
However this is what actually happened:
handleClick
is calledsetA
setA
and setB
. Let combine them and run them at once instead of one by onesetA
and setB
run at the same timea
and state variable b
change at the same timeuseEffect
is called---> We only have ONE re-render and ONE run of useEffect
callback
This is what state batching does: it combines multiple state-update functions into one "batch" and run all these functions at once
But why do we need state batching?
As you can see in the example above, without state batching we need to run an additional re-render of component and an additional run of useEffect
callback. This can be worse if we have more state variables compared to our example. Batching saves us time and resource.