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