Raja Muhammad Asher
Raja Muhammad Asher

Follow

Raja Muhammad Asher

Follow
useState Lazy Initialization

Photo by Lautaro Andreani on Unsplash

useState Lazy Initialization

Raja Muhammad Asher's photo
Raja Muhammad Asher
·Mar 4, 2023·

1 min read

In React's useState hook, lazy initialization refers to initializing the state with a function instead of a direct value.

Lazy initialization is useful when the initial state value requires some computation or relies on the current state or props. By passing a function as the initial value, React calls that function only during the initial rendering, ensuring the correct value is computed.

Here's an example:

import React, { useState } from 'react';

function Counter() {
  const [count, setCount] = useState(() => {
    // Some complex computation or logic
    return 0;
  });

  // ...
}

In the above example, the useState hook is used to create a state variable count, initialized with the result of the function () => 0. The function will be called only during the initial rendering.

Using lazy initialization can improve performance and prevent unnecessary computations if the initial state value is costly to compute.

 
Share this