inconsistent behaviour with strict mode and useEffect
See original GitHub issueI have a component which is subscribed to value
from my store, which it uses in it’s render output. I attempted to add a useEffect which would trigger when value changed, and perform some side effect, e.g:
function Effect() {
const value = useStore(state => state.value);
useEffect(() => {
someSideEffect(value)
}, [value]);
return value;
}
I noticed that the useEffect wasn’t firing when the value changed, despite the rendered output updating.
Eventually i reduced this down to React.StrictMode
, if i remove this, everything works how I expect it to, but when it’s on, value changing just caused the component to render 4 times with no useEffect calls.
Minimal example: https://codesandbox.io/s/hungry-hoover-khx8k
But! It gets even weirder than that… 😫
If you look in the codesandbox, you can see that when using StrictMode, calling test()
in the console will not cause the effect to fire, but pressing the button, which fires the same update function, only grabbed via useStore
, works fine.
There is also a version of the Effect component in the sandbox which uses the more direct api.subscribe
style of useEffect, and this one works with both the button and the test()
function call, even with strict mode turned on.
I can’t get my head around it. Am I doing something wrong?
Issue Analytics
- State:
- Created 3 years ago
- Reactions:4
- Comments:12 (3 by maintainers)
Top GitHub Comments
Ahhh ok, yeah I think I get it now. It’s not so much that the code itself is outside the react tree, but the event that triggers the state change was a react synthetic event (the click handler on the button in this case).
I’m not sure this gets me any closer to a workable solution, but it sure is expanding my knowledge of react inner workings, so thanks again for your help.
On Tue, 16 Jun 2020, 22:19 Renaud Déchaux, notifications@github.com wrote:
Right, that should have it back to the original minimal reproduction of the original issue, sorry about that.
I’d be very keen to get your opinion again, it’s entirely possible that i’m just making a simple mistake somewhere, and to be honest at this point I hope that I am. Am I wrong in expecting the useEffect to fire when calling
test()
in the console?