react: Bug: useSyncExternalStore does not schedule update after mutation
Here is a Replay recording with comments: https://app.replay.io/recording/318114a4-3102-4732-ad1b-cb63b9c0ac22
I think the comments I’ve added show the following scenario:
- A React component (
Subscriber) usesuseSyncExternalStoreto read from a mutable store. - The Activity subtree containing
Subscriberis hidden, and React unsubscribes from the store. - An update is scheduled to show the hidden subtree again and the
Subscribercomponent re-renders (with memoized state). - A parent component mutates the store in a layout effect. (The
Subscribercomponent is not yet listening and so it does not re-render to reflect the updated store value.) - React re-subscribes the
Subscribercomponent (useSyncExternalStore) but it has already missed the mutation and React does not check for a changed snapshot value.
We originally observed this behavior in Replay itself but I was able to reduce it to the following simplified case: https://codesandbox.io/s/inspiring-bird-m4wv5l
I’ve added comments to the Replay, including ones that bracket the problematic commitRoot. Here’s a short Loom as well talking through the bug:
https://www.loom.com/share/2584cad5b4c44e6bba396ff8cf79db1d
I think an application could work around this issue in a couple of ways:
- Only mutate stores in passive effects. (This may cause visible layout shift though so it seems bad.)
- Mutable store users should avoid memoized
getSnapshotandsubscribefunctions. (This would schedule some unnecessary effects work which is probably nice to avoid but maybe acceptable.) - Store subscribe methods should always invoke the
callbackReact passes. (This would cause a lot of unnecessaryObject.iscomparisons but that’s probably an acceptable cost.)
I think the third option above seems best, but needing to do that feels like a foot gun for the API. Thoughts?
cc @acdlite, @sebmarkbage in case you find this interesting.
About this issue
- Original URL
- State: open
- Created 3 years ago
- Reactions: 1
- Comments: 15 (7 by maintainers)
Commits related to this issue
- Workaround useSyncExternalStore+Offscreen bug (#9878) For more context see facebook/react#27670 — committed to replayio/devtools by bvaughn 3 years ago
- Add failing test for issue #27670 — committed to facebook/react by bvaughn 3 years ago
- Add failing test for issue #27670 — committed to facebook/react by bvaughn 3 years ago
Reproed the linked codesandbox has the same issue on 19.0.0-experimental-0bc30748-20241028.
The scope of the bug I’ve reported here requires Offscreen/Activity.
@eps1lon I already wrote a test for this in PR #27676