admin管理员组文章数量:1332710
Normally when we need to update a state in a functional ponent, we do something like this:
function Example() {
const [count, setCount] = React.useState(0);
return (<div><p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>);
}
When and why will we ever need to use the functional update form?
function Example() {
const [count, setCount] = React.useState(0);
return (<div><p>You clicked {count} times</p>
<button onClick={() => setCount(c=>c + 1)}>
Click me
</button>
</div>);
}
Normally when we need to update a state in a functional ponent, we do something like this:
function Example() {
const [count, setCount] = React.useState(0);
return (<div><p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>);
}
When and why will we ever need to use the functional update form?
function Example() {
const [count, setCount] = React.useState(0);
return (<div><p>You clicked {count} times</p>
<button onClick={() => setCount(c=>c + 1)}>
Click me
</button>
</div>);
}
Share
Improve this question
asked Aug 16, 2021 at 3:53
Chong Lip PhangChong Lip Phang
9,2797 gold badges75 silver badges114 bronze badges
3
-
4
When you know that
newState
is dependent on theprevious
state. Simple – DecPK Commented Aug 16, 2021 at 3:57 -
@DecPK Is it safe to say that for operations such as incrementing the state variable by
x
, we should always dosetState(count => count + 1)
instead ofsetState(count+1)
– Murtuza Commented Jan 25, 2024 at 5:19 -
1
@Murtuza Not necessary when you are using functional update you will get the latest value at that time. and when you use just
count + 1
thencount
will be taken from closure. – DecPK Commented Jan 26, 2024 at 7:48
6 Answers
Reset to default 4Use the function form when the setter may close over an old state value.
For example, if an async request is initiated, and you want to update state after that's done, the request that was made will have scope of the state as it was at the beginning of the request, which may not be the same as the most up-to-date render state.
You may also need to use the function form if the same state value was just updated, eg
setValue(value + 1);
// plicated logic here
if (someCondition) {
setValue(value => value + 1);
}
because the second call of setValue
closes over an old value
.
State Updates May Be Asynchronous:
https://reactjs/docs/state-and-lifecycle.html#state-updates-may-be-asynchronous
useState
is the same as setState in this condition.
You can see the different when call set state twice:
<button
onClick={() => {
setCount(count + 1);
setCount(count + 1);
}}
></button>;
<button
onClick={() => {
setCount(c => (c + 1));
setCount(c => (c + 1));
}}
></button>;
There are other use cases too. For example, when you call useState
inside an effect. If new state is dependent on old state, this might cause an infinite loop.
useEffect(() => {
setCounter(counter + 1);
}, [counter]);
You can avoid this by using functional updates:
useEffect(() => {
setCounter(old => old + 1);
}, []);
The functional update form also allows the update function to be passed to its children while still having access to the parent’s state.
function MyButton(props){
// return <button onClick={()=>props.onClick(count+1)}>+1</button>; // error as count is not exposed 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>);
}
ReactDOM.render(<Example/>,document.querySelector("div"));
According to this: https://reactjs/docs/state-and-lifecycle.html#state-updates-may-be-asynchronous
The the functional update
form make sure that the previous state that you take reference from is the latest / finalized version when there might be multiple setState hook (which is asynchronous) called (for example, if the user spam click on the button)
And also due to its async nature, the state will not be updated right away within a function, for e.g:
func() {
console.log(counter) // counter = 1
setCounter(counter => counter + 1) // counter = 1
console.log(counter) // counter = 1
}
本文标签: javascriptWhen to use functional update form of useState() hookeg setX(xgtx1)Stack Overflow
版权声明:本文标题:javascript - When to use functional update form of useState() hook, eg. setX(x=>x+1) - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742243888a2439006.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论