When to use useState initial value as function?

You use it when you want the computation of that initial state to happen only once.

Because if you use an expression instead say:

const [state, setState] = useState(compute());

React saves the initial result of compute() once and ignores it on the next renders. But the compute function is still called on each render. This can be wasteful.

If you pass a function instead, the function is invoked only once.

From the docs:

const [state, setState] = useState(initialState);

The initialState argument is the state used during the initial render.
In subsequent renders, it is disregarded. If the initial state is the
result of an expensive computation, you may provide a function
instead, which will be executed only on the initial render

const [state, setState] = useState(() => {
      const initialState = someExpensiveComputation(props);
      return initialState;
});

Also, in case you pass function as the argument to useState like the question is asking, it must satisfy certain requirements:

If you pass a function as initialState, it will be treated as an initializer function. It should be pure, should take no arguments, and should return a value of any type. React will call your initializer function when initializing the component, and store its return value as the initial state.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)