React has a hook called useState, which is used when adding state to functional components.
useState
This is documented here:
Lazy initial state
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; });
Passing a callback to setState
also calls the callback, but for a different reason:
Functional updates
If the new state is computed using the previous state, you can pass a function to setState. The function will receive the previous value, and return an updated value. Here’s an example of a counter component that uses both forms of setState:
function Counter({initialCount}) { const [count, setCount] = useState(initialCount); return ( <> Count: {count} > ); }