MENU
Functional Update
If the new state is computed using the previous state, you can pass a function to setState, to make sure it gets the updated state.
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 [count, setCount] = React.useState(0);
return (<div><p>Counter: {count}</p>
<button onClick={() => {
setCount(count+1); // asynchronous
setCount(count+1); // still gets the old 'count' value
}}>+1</button>
<button onClick={() => {
setCount(count+1);
setCount(c=>(c+1)); // waits for previous update first
}}>+2</button>
<button onClick={() => {
setCount(count+1);
setCount(c=>(c+1)); // asynchronous too
setCount(count+1); // still gets the initial 'count' value
}}>+1</button>
</div>);
}
const root = ReactDOM.createRoot(document.querySelector("div"));
root.render(<Example/>);
</script>
</body></html>The functional update form also allows the update function to be passed to its children while still having access to the parent's state. This also allows us to pass data from the child component to the parent component.
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 MyButton(props) {
// return <button onClick={()=>props.onClick(count+1)}>+1</button>; // error: count is not defined here
return <button onClick={()=>props.onClick(n=>(n+1))}>+1</button>;
}
function Example() {
const [count, setCount] = React.useState(0);
return (<div><p>Counter: {count}</p>
<MyButton onClick={setCount}/>
</div>);
}
const root = ReactDOM.createRoot(document.querySelector("div"));
root.render(<Example/>);
</script>
</body></html>