DEV Community

Cover image for React useState lazy initialization in one glance
Thiyagaraj T
Thiyagaraj T

Posted on

 

React useState lazy initialization in one glance

How

useState is the simplest React hook out in wild but it has a very interesting feature — lazy initialization
If you provide useState with a function, then it will be executed only on the initial render.


// For every render
const [state, setState] = useState(window.localStorage.getItem("key"));

// Lazy Initialization - Only once
const [state, setState] = useState(() => window.localStorage.getItem("key"));

Enter fullscreen mode Exit fullscreen mode

When to use

Any function that is computationally expensive can be initialized lazily.

Reference
https://reactjs.org/docs/hooks-reference.html#usestate

Top comments (0)

typescript

11 Tips That Make You a Better Typescript Programmer

1 Think in {Set}

Type is an everyday concept to programmers, but it’s surprisingly difficult to define it succinctly. I find it helpful to use Set as a conceptual model instead.

#2 Understand declared type and narrowed type

One extremely powerful typescript feature is automatic type narrowing based on control flow. This means a variable has two types associated with it at any specific point of code location: a declaration type and a narrowed type.

#3 Use discriminated union instead of optional fields

...

Read the whole post now!