Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use useState initial value as function?

What is the case where you use useState's initial value as a function?
Is there any difference from just passing a value?

e.g.

const [state, setState] = useState(() => someValue)
like image 482
Vencovsky Avatar asked Feb 07 '20 19:02

Vencovsky


People also ask

Can I initialize useState with a function?

With the useState hook, you can pass a function as an argument to initialize the state lazily. As discussed, the initial value is needed only once at the first render. There is no point in performing this heavy computation on the subsequent renders. const [counter, setCounter] = useState(() => Math.

What is the best practice to use function useState hook?

Instead, always use Hooks at the top level of your React function, before any early returns. By following this rule, you ensure that Hooks are called in the same order each time a component renders. That's what allows React to correctly preserve the state of Hooks between multiple useState and useEffect calls.

What is the initial value of useState?

The key difference is that the initial value of the state defined by useState can be anything you want it to be. It no longer has to be an object. A string, a number, an object, undefined , null - anything goes!

How do I set initial value in useState?

To set a conditional initial value for useState in React:Pass a function to the useState hook. Use a condition to determine the correct initial value for the state variable. The function will only be invoked on the initial render.


2 Answers

I think it is more or less clear 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;
});
like image 149
Giorgi Moniava Avatar answered Sep 22 '22 14:09

Giorgi Moniava


If you want to use useState's initial value as a function, you need to use currying :

const [state, setState] = useState(() => () => someValue);

This is because in the documentation, useState executes the provided function and considers its result as the initial value. Using currying, () => someValue is returned and considered to be the intial value.

like image 20
Etienne Tonnelier Avatar answered Sep 24 '22 14:09

Etienne Tonnelier