Skip to content

Commit c5c473d

Browse files
docs: zustand/context correct doc, added snippets (#433)
* docs: zustand/context correct doc, added snippets * docs: corrected review points * docs: createContext summary change
1 parent df6fd1d commit c5c473d

File tree

1 file changed

+55
-2
lines changed

1 file changed

+55
-2
lines changed

readme.md

Lines changed: 55 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -456,10 +456,10 @@ import createContext from 'zustand/context'
456456

457457
const { Provider, useStore } = createContext()
458458

459-
const store = create(...)
459+
const createStore = () => create(...)
460460

461461
const App = () => (
462-
<Provider initialStore={store}>
462+
<Provider initialStore={createStore()}>
463463
...
464464
</Provider>
465465
)
@@ -470,6 +470,59 @@ const Component = () => {
470470
...
471471
}
472472
```
473+
<details>
474+
<summary>createContext usage in real components</summary>
475+
476+
```jsx
477+
import create from "zustand";
478+
import createContext from "zustand/context";
479+
480+
// Best practice: You can move the below createContext() and createStore to a separate file(store.js) and import the Provider, useStore here/wherever you need.
481+
482+
const { Provider, useStore } = createContext();
483+
484+
const createStore = () =>
485+
create((set) => ({
486+
bears: 0,
487+
increasePopulation: () => set((state) => ({ bears: state.bears + 1 })),
488+
removeAllBears: () => set({ bears: 0 })
489+
}));
490+
491+
const Button = () => {
492+
return (
493+
{/** store() - This will create a store for each time using the Button component instead of using one store for all components **/}
494+
<Provider initialStore={createStore()}>
495+
<ButtonChild />
496+
</Provider>
497+
);
498+
};
499+
500+
const ButtonChild = () => {
501+
const state = useStore();
502+
return (
503+
<div>
504+
{state.bears}
505+
<button
506+
onClick={() => {
507+
state.increasePopulation();
508+
}}
509+
>
510+
+
511+
</button>
512+
</div>
513+
);
514+
};
515+
516+
export default function App() {
517+
return (
518+
<div className="App">
519+
<Button />
520+
<Button />
521+
</div>
522+
);
523+
}
524+
```
525+
</details>
473526
474527
## TypeScript
475528

0 commit comments

Comments
 (0)