Skip to content

Commit

Permalink
fix(docs): zustand v3 context migration doc (#2039)
Browse files Browse the repository at this point in the history
* fix(docs): zustand v3 context migration doc

* Update docs/previous-versions/zustand-v3-create-context.md

Co-authored-by: Blazej Sewera <code@sewera.dev>

* Update docs/previous-versions/zustand-v3-create-context.md

Co-authored-by: Blazej Sewera <code@sewera.dev>

* Update docs/previous-versions/zustand-v3-create-context.md

Co-authored-by: Blazej Sewera <code@sewera.dev>

---------

Co-authored-by: Blazej Sewera <code@sewera.dev>
  • Loading branch information
dai-shi and sewera authored Sep 11, 2023
1 parent 504aa40 commit db76eba
Showing 1 changed file with 31 additions and 18 deletions.
49 changes: 31 additions & 18 deletions docs/previous-versions/zustand-v3-create-context.md
Original file line number Diff line number Diff line change
Expand Up @@ -107,25 +107,38 @@ export default function App({ initialBears }) {
Discussion: https://github.com/pmndrs/zustand/discussions/1276
Here's the diff showing how to migrate from v3 createContext to v4 API.
Here's the new context usage with v4 API.
```diff
// store.tsx
+ import { createContext, useContext } from "react";
- import create from "zustand";
- import createContext from "zustand/context";
+ import { createStore, useStore } from "zustand";

- const useStore = create((set) => ({
+ const store = createStore((set) => ({
bears: 0,
increasePopulation: () => set((state) => ({ bears: state.bears + 1 })),
removeAllBears: () => set({ bears: 0 })
}));
```jsx
import { createContext, useContext, useRef } from 'react'
import { createStore, useStore } from 'zustand'

const StoreContext = createContext(null)

const StoreProvider = ({ children }) => {
const storeRef = useRef()
if (!storeRef.current) {
storeRef.current = createStore((set) => ({
// ...
}))
}
return (
<StoreContext.Provider value={storeRef.current}>
{children}
</StoreContext.Provider>
)
}

+ const MyContext = createContext()
const useStoreInContext = (selector) => {
const store = useContext(StoreContext)
if (!store) {
throw new Error('Missing StoreProvider')
}
return useStore(store, selector)
}
```
+ export const Provider = ({ children }) => <MyContext.Provider value={store}>{children}</MyContext.Provider>;
Or reach out to some third-party libraries that provide Zustand v3-like APIs:
+ export const useMyStore = (selector) => useStore(useContext(MyContext), selector);
```
- <https://github.com/charkour/zustand-di>
- <https://github.com/arvinxx/zustand-utils>

1 comment on commit db76eba

@vercel
Copy link

@vercel vercel bot commented on db76eba Sep 11, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please sign in to comment.