Is use-sync-external-store really required if you use createWithEqualityFn from zustand/traditional? #2791
-
|
I thought use-sync-external-store was just a polyfill for people on old versions of React, but the migration docs seem to say you need it, and I do indeed get a build error if I don't have it: Also the docs website seems pretty flaky. Sometimes clicking links does nothing, sometimes search returns nothing, sometimes it's an error page like "Application error: a client-side exception has occurred (see the browser console for more information).". I'm using the latest version of Firefox. |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 5 replies
-
|
@dumbmatter we're working on revamping docs, basically migrating away from nextjs to vitepress. |
Beta Was this translation helpful? Give feedback.
-
|
Thanks @dumbmatter, installing
Shouldn't that be a dependency if it is needed for Zustand? |
Beta Was this translation helpful? Give feedback.
-
|
I ended up writing a small "createWithEqualityFn" hook myself, instead of adding another dep. import { useRef } from "react";
import { shallow } from "zustand/shallow";
export function useStableDerivedObject<TState, TDerived extends object>(
selector: (state: TState) => TDerived,
options: { isEqual: (a: TDerived, b: TDerived) => boolean },
) {
const isEqual = options.isEqual ?? shallow;
const prev = useRef<TDerived>(undefined);
return (state: TState) => {
const next = selector(state);
if (prev.current === undefined || !isEqual(prev.current, next)) {
prev.current = next;
}
return prev.current;
};
}usage like const addresses = useMyStore(
useStableDerivedObject<MyStore, Address[]>((state) => state.addresses, {
isEqual: (A, B) => A.length === B.length && A.every((_, idx) => A[idx].id === B[idx].id),
}),
); |
Beta Was this translation helpful? Give feedback.
@dumbmatter we're working on revamping docs, basically migrating away from nextjs to vitepress.
zustand/traditionalrelies onuse-sync-external-store