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)
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.
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.
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!
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.
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;
});
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With