skip to Main Content

I want to use React’s useSyncExternalStore hook to, well, sync data from an external store. However, I’m running into issues because it uses Object.is to compare values to decide when to re-render and that doesn’t work because my data is an array. (Object.is of any arrays will always be false, even if their contents are the same, because it’s not the same array in memory)

Is there a way to override this with a custom comparison function?

I tried serializing the array to JSON and back, and that seems to make everything work. However, that is obviously not ideal as I can’t take the performance hit of having to serialize back-and-forth.

2

Answers


  1. Is there a way to override this with a custom comparison function?

    No, there isn’t. useSyncExternalStore is built to expect immutable data (which is in line with react’s general approach)

    See the caveats section in react’s documentation

    • The store snapshot returned by getSnapshot must be immutable. If the underlying store has mutable data, return a new immutable snapshot if the data has changed. Otherwise, return a cached last snapshot.
    Login or Signup to reply.
  2. The useSyncExternalStore hook in React does not provide a built-in way to override the value comparison function. However, you can create a wrapper function that performs a deep comparison of your array values before passing them to the hook. One way to achieve this is by using a library like lodash.isEqual or implementing your own deep equality check function. This approach avoids the performance overhead of serializing and deserializing the data while ensuring that the component re-renders correctly when the array contents change.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search