MENU
Functional Update
<br>
<br>
<br>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
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)); // asynchrnous too
setCount(count+1); // still gets the initial ‘count’ value
}}>+1</button>
</div>);}ReactDOM.render(<Example/>,document.querySelector("div"));
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
function MyButton(props){ // return <button onClick={()=>props.onClick(count+1)}>+1</button>; // error
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>);}ReactDOM.render(<Example/>,document.querySelector("div"));