React useState callback function

What is the callback function in a useState for?

Friday, October 22, 2021

lazy cat

Why do we need to pass a callback function to the useState function

TL;DR version

We can pass a callback function when calling useState to take advantage of lazy initialization.

This will resolve the source of the state only once, thus avoiding unnecessary computation during re-renders.

Longer version

When we develop real production applications, we do not always derive our state from simple primitive values. Sometimes we need to calculate them based on other values, as shown below.


You might notice the logics to get the default value are very identical so as a good programmer, we can extract the logic to a new function to avoid duplication.


The problem occurs when the source of our state is computationally expensive. Every time we re-render our component, we need to re-evaluate our default state. Try to see the problem by playing with the code below.


Each time we click the button, the complexFunction will always be called(verify by uncommenting console.log or alert). If that complexFunction is computationally expensive, then expect our component will render slower.


Solution: perform a lazy initialization

For a such big word like lazy initialization it actually is very simple. We simply need pass a function instead of a value as shown below.



Try to play with the code below and see the difference


The complexFunction will evaluate only once if we pass it as a function and not invoking it immediately, thus giving us a performance boost.


Do we need to always lazy initialize our state?

No. It's not magic that allows lazy initialization to do the above optimization. There's an overhead to it which means if we use it everywhere, it could make our component "slower" in contrast to our goal to make it faster.



Conclusion

Use lazy initialization when your state depends on something that is computationally heavy. Avoid unnecessary "optimization"; lazy initialization has a small overhead, so use it wisely.