Init Callback
(Only text explanation)Initial value can cost expensive on react on the first render.
Maybe it is parsing a giant JSON object, like just an enormous JSON object or something. Or it's like a string of JSON is parsing that to calculate this initial value.
React is going to call our function every time whenever we update this value, then this computation is going to happen every time.
Remember that the initial value only matters on the initial render. So having this computation every single render after the first is unnecessary because it's going to be ignored after that initial render. So that is kind of wasteful.
React will re-render our components. We'll pass it this function again that does this computation.
Passing value useState as a function ✅
Then you don't bother creating that variable every single time you render.
const [val, setVal] = useState(() => {
const initialVal = calculateInitialValue();
return initialVal;
});Perform a computation unnecessarily
const initialVal = calculateInitialValue();
const [val, setVal] = useState(initialVal);