UseState performance features

UseState performance features

Lazy initialization and update with function

I just came across two lesser-known features of the useState hook in React :

1 - Lazy initialization

Rather than simply passing the initial state you can call useState with a function that returns the initial state. This way, the initial value is only retrieved the first time the component is rendered and not every re-render. Pretty useful when that first value is computationally expensive.

2 - Update state with a function

To avoid issues with closures, rather than passing the new value to the dispatch function (the setter) you can pass an anonymous function with the current value you want to update. That way you always get access to the latest value of that variable.

More info in this article by Kent C. Dodds and also in this video by Web Dev Simplified.