admin管理员组文章数量:1336311
I have this simple code:
const [state, setState] = useState([]);
useEffect(() => {
socket.on('something', data => {
console.log('ONE');
setState(old => {
console.log('TWO');
const newArr = [...old];
// do something to newArr
return newArr;
});
});
return () => {
socket.off('something');
};
}, []);
Everything works as intended but for some reason the something
callback triggers once (the ONE
is printed once), but inside when I set the state, the setState
callback is called twice (it prints TWO
twice). Why is that?
I have this simple code:
const [state, setState] = useState([]);
useEffect(() => {
socket.on('something', data => {
console.log('ONE');
setState(old => {
console.log('TWO');
const newArr = [...old];
// do something to newArr
return newArr;
});
});
return () => {
socket.off('something');
};
}, []);
Everything works as intended but for some reason the something
callback triggers once (the ONE
is printed once), but inside when I set the state, the setState
callback is called twice (it prints TWO
twice). Why is that?
- 4 This is done on purpose in development mode. – Patrick Roberts Commented May 1, 2020 at 13:22
- @PatrickRoberts, oh i see, so... how do i avoid it? – TheNormalPerson Commented May 1, 2020 at 14:16
- You don't. In production mode it won't do that, and in development mode, it's done to quickly reveal issues if you perform mutations or store state externally to react hooks. In short, nothing's wrong and nothing needs to be fixed. – Patrick Roberts Commented May 1, 2020 at 15:02
1 Answer
Reset to default 10This is a feature of React's strict mode (no, it's not a bug).
The setState()
updater function, among other methods, is invoked twice in a strict context during development mode only in order to quickly reveal mon antipatterns, including state mutations and externally managed state.
These efforts are in preparation for the uping concurrent mode, which is expected to regularly invoke these methods multiple times per render as the internal implementation of react's render phase grows more plex.
In short, nothing needs to be fixed. React is just making it easier for you to discover logic errors in development while staying performant in production.
本文标签: javascriptAny reason for a react state hook set callback to fire twiceStack Overflow
版权声明:本文标题:javascript - Any reason for a react state hook set callback to fire twice? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742336135a2455663.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论