Search code examples
reactjsreact-hooks

Using `useSyncExternalStore` with a custom equality comparitor?


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.


Solution

  • 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.