Combining Zustand + useContext #165
Replies: 1 comment 11 replies
-
I think this use case is valid with caveats. This is why we don't document this use case, and recommend creating hooks at module level and import them. const useStore = create(...);
export const useGlobalStore = () => {
return {
quantity: useStore(state => state.quantity),
increaseQuantity: useStore(state => state.increaseQuantity),
decreaseQuantity: useStore(state => state.decreaseQuantity),
resetQuantity: useStore(state => state.resetQuantity),
};
}; |
Beta Was this translation helpful? Give feedback.
11 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
I couldn't find a code example of combining Zustand with useContext to manage global state. So I quickly put something together. It's a super simple App to show different components that each call and update the same store.
But I'm not entirely sure if the approach I've taken – while it works – is most efficient.
https://github.com/SimeonGriggs/zustand-useContext
Specifically, I'm using different methods in each component. Two components pull the store from Context, another uses a custom hook to pull the store from Context.
The aim here was to retrieve items from store with the least amount of code. The custom hook is less code, but requires double-handling everything from the store.
I'm curious to get feedback on the approach being demonstrated here if anyone has the time to take a look.
Beta Was this translation helpful? Give feedback.
All reactions