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:

  1. A React component (Subscriber) uses useSyncExternalStore to read from a mutable store.
  2. The Activity subtree containing Subscriber is hidden, and React unsubscribes from the store.
  3. An update is scheduled to show the hidden subtree again and the Subscriber component re-renders (with memoized state).
  4. A parent component mutates the store in a layout effect. (The Subscriber component is not yet listening and so it does not re-render to reflect the updated store value.)
  5. React re-subscribes the Subscriber component (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 getSnapshot and subscribe functions. (This would schedule some unnecessary effects work which is probably nice to avoid but maybe acceptable.)
  • Store subscribe methods should always invoke the callback React passes. (This would cause a lot of unnecessary Object.is comparisons 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

Most upvoted comments

Reproed the linked codesandbox has the same issue on 19.0.0-experimental-0bc30748-20241028.

This is only a bug when used with Activity or does it also happen when a suspended tree unsuspends?

The scope of the bug I’ve reported here requires Offscreen/Activity.

I’m still trying to write a test for it so that we can pick it up again at a later stage.

@eps1lon I already wrote a test for this in PR #27676