https://github.com/benbowes/zustand-context-api-pattern
https://github.com/benbowes/zustand-context-api-pattern
Last synced: over 1 year ago
JSON representation
- Host: GitHub
- URL: https://github.com/benbowes/zustand-context-api-pattern
- Owner: benbowes
- Created: 2024-12-07T09:51:42.000Z (over 1 year ago)
- Default Branch: master
- Last Pushed: 2024-12-08T11:43:11.000Z (over 1 year ago)
- Last Synced: 2025-02-03T09:48:01.988Z (over 1 year ago)
- Language: TypeScript
- Size: 42 KB
- Stars: 0
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# A Zustand + Context API pattern for making use of the best of both worlds.
This pattern comes from here: https://tkdodo.eu/blog/zustand-and-react-context
And I discovered it here from Cosden (https://www.youtube.com/@cosdensolutions): https://www.youtube.com/watch?v=1Fi4hK7L1ec
### Getting started
`npm i`
`npm run dev`
The main files to look at are `CountProvider.tsx` and `App.tsx`.
## Notes
When adding a `` under the context api provider ``, the `` does not re-render.
It is not affected by changes in state by Zustand, and this is very good!
You can check the console logs to see the results.
Every component renders on first load, and this is expected. However, only the components that subcribe to the Zustand store via the `useCountStore` hook re-render when the `CountProvider` is updated via the Zustand commands that update Zustand state.
---
#### What I see as the key benefits of this pattern.
- everything under a context api provider is not unnecessarily re-rendered.
- testing becomes easier, as you can provide a component that is reliant on Zustand with initial state - so setup and teardown of tests will be easy with this pattern.