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.
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1742336136a4424688.html
评论列表(0条)