Context store will get reseted when parent component re-renders #2292
-
|
Hi, I'm playing with store in a context as per this documentation https://docs.pmnd.rs/zustand/guides/initialize-state-with-props associated to this codesandbox: https://codesandbox.io/p/sandbox/4jn1e2 I found that if the component where the provider is used re-renders then the whole store will get reset. To illustrate this I forked the code sandbox above here: https://codesandbox.io/p/sandbox/practical-lena-llnwz5 I added a Is that a bug or is that intended? Thanks |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 5 replies
-
|
Figured it out. The reason is that the context provider is creating a new store within the render method: const MyProvider = ({ children }: { children: ReactNode }) => {
const store = createMyStore();
return <MyContext.Provider value={store}>{children}</MyContext.Provider>;
};Memoizing the store will do the trick: const MyProvider = ({ children }: { children: ReactNode }) => {
const store = useMemo(() => {
return createMyStore();
}, []);
return <MyContext.Provider value={store}>{children}</MyContext.Provider>;
}; |
Beta Was this translation helpful? Give feedback.
@gsouf the right way to do it is by using
useRefinstead ofuseMemoRef: https://docs.pmnd.rs/zustand/guides/initialize-state-with-props