Open xixixao opened 2 months ago
Shortly after I wrote this up I had a revelation that I can control the ordering by performing my useEffect
in extra child components the parent adds. So I guess the parent component does have full control over when it executes useEffects
. This might be nice to document.
Interesting find. Do we have the same behavior in the latest React 19 RC?
@xixixao I've noticed this behaviour is the same with or without StrictMode
, so it doesn't seem to be related to it.
Anyway, following this @gaearon's comment, this seems expected, though the order depends on whether those components are mounted or have to be unmounted:
child -> parent
.parent -> child
.To demonstrate it, I've extended your reproduction and added a simple trigger to change the state:
A
and B
are mounted, their cleanup order is always B -> A
.Although I think this is 100% expected from React, maybe it should be clearer in the docs.
built an app to get paid for this PR https://www.n0va-io.com/discover/facebook/react
React version: 18.2 or 18.3
Steps To Reproduce
Link to code example: https://codesandbox.io/s/sleepy-bhabha-q5tfnt?file=/src/App.js
The current behavior
Notice that during the strict mode cycle, the child effect cleanup runs before the parent's. But during actual unmounting, the child effect cleanup runs after the parent's.
The expected behavior
I expected the behavior to match.
Why does this matter
From my investigations:
order
andchild
on this page: https://react.dev/reference/react/useEffectThe scenario we're trying to implement is for the parent to provider authentication state and for children to be subscribed and depend on this external authentication state.
Ideally we'd want:
We achieved the first with useLayoutEffect (isomorphic for SSR) in parent, and useEffect in child.
But now I'm realizing there might be no easy way to achieve the second, without deferring the cleanup to another tick while avoiding racing with another render.
Also note that from my testing this popular SO answer on this topic is wrong: https://stackoverflow.com/a/55028488/1526986