cft

UseState: try to be lazy

I just came across two lesser-known features of the useState hook in React: lazy initialization and update state with a function.


user

Daniel Martorell

3 years ago | 1 min read

Lazy initialization and update state with a 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.

Upvote


user
Created by

Daniel Martorell

Javascript Developer || React JS & CSS enthusiast


people
Post

Upvote

Downvote

Comment

Bookmark

Share


Related Articles