MENU
Functional State Initialization
If you call a function to compute the initial value with useState(), the function will be executed on every render.
RESETRUNFULL
RESETRUNFULL
<!DOCTYPE html><html>
<head>
<meta charset="UTF-8" />
<script src="https://unpkg.com/react@18/umd/react.development.js" crossorigin></script>
<script src="https://unpkg.com/react-dom@18/umd/react-dom.development.js" crossorigin></script>
<script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>
</head>
<body>
<div></div>
<script type="text/babel">
function Example() {
const f = n=>{console.log('firing '+n); return n;};
const [a, setA] = React.useState(f(0)); // calling a function
const [b, setB] = React.useState(()=>f(1)); // passing a raw function
return (<div><p>{a} {b}</p>
<button onClick={() => {setA(a+1);}}>firing f(0) on every render</button>
<button onClick={() => {setB(b+1);}}>firing f(1) on first render only</button>
</div>);
}
const root = ReactDOM.createRoot(document.querySelector("div"));
root.render(<Example/>);
</script>
</body></html>If you update a State Hook to the same value (true Object.is(a,b)) as the current state, React will bail out without rendering the children or firing effects.