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?
The setState()
updater function, among other methods, is invoked twice in a strict context during development mode only in order to quickly reveal common antipatterns, including state mutations and externally managed state.
These efforts are in preparation for the upcoming 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 complex.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With