Leonard Kioi Kinyanjui
Lenny's Blog

Lenny's Blog

React useState lazy initializers

Photo by Mike van den Bos on Unsplash

React useState lazy initializers

Leonard Kioi Kinyanjui's photo
Leonard Kioi Kinyanjui
·Feb 14, 2022·

2 min read

When using useState to manage state for a React component you normally do something like this:

function Counter() {
  const [count, setCount] = useState(0);
  ...
}

0 above is the initial value that count will be set to.

If getting the initial value involves some calculation or some other operation such as fetching the value from local storage, you would factor this out into a function. You can also pass a function as a parameter to useState. React will call the function and use the return value as the initial value:

const fetchCount() {
  return 0 // pretend this is an expensive calculation :)
}

function Counter() {
  const [count, setCount] = useState(fetchCount());
  ...
}

Remember that React will call this function on every render, so for an expensive calculation, the user would notice a lag in the re-render leading to a degraded user experience.

The solution to this is lazy initializers. This simply means passing a function to useState without calling the function:

const fetchCount() {
  return 0 // pretend this is an expensive calculation :)
}

function Counter() {
  const [count, setCount] = useState(fetchCount);
  ...
}

We only need the initial value the first time the component is mounted and this is the only time React will call the lazy initializer.

Lazy initializers are a performance optimization that you can take advantage of in your code.

 
Share this