-
-
Notifications
You must be signed in to change notification settings - Fork 1.6k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
createContext not working as expected #432
Comments
It seems like working now. The mistake was I initiated the store outside from the component. So, it was using the same store for all the components instead of creating a new store. overall code import "./styles.css";
import create from "zustand";
import createContext from "zustand/context";
const { Provider, useStore } = createContext();
// Before store = create(...)
const store = () =>
create((set) => ({
bears: 0,
increasePopulation: () => set((state) => ({ bears: state.bears + 1 })),
removeAllBears: () => set({ bears: 0 })
}));
const Button = () => {
return (
<Provider initialStore={store()}>
{/** Before - initialStore={store} */}
<ButtonChild />
</Provider>
);
};
const ButtonChild = () => {
const state = useStore();
return (
<div>
{state.bears}
<button
onClick={() => {
state.increasePopulation();
}}
>
+
</button>
</div>
);
};
export default function App() {
return (
<div className="App">
<Button></Button>
<Button></Button>
</div>
);
} |
I originally suggested to pass |
Yes, the documentation is incorrect. |
Mind opening a PR? |
Sure. I'm on it. |
Hey everyone, I just tried to use the createContext API but it seems saving the state in a global and updating changes to all the contexts instead of the particular single context.
Here is the reproducible code sandbox link - here
This is the expected result here
The text was updated successfully, but these errors were encountered: