State Management · Senior · Question 57 of 75
How do you give each instance of a complex widget its own Zustand store?
const StoreContext = createContext(null);
function Editor({ initial }) {
const [store] = useState(() => createStore(() => ({ ...initial })));
return <StoreContext value={store}>...</StoreContext>;
}- ✓Correct answer: Create a vanilla store per instance (
createStore) and provide it via Context, reading it withuseStore(store, selector) - 2Zustand stores are always global singletons
- 3Call
create()inside the component body on every render
Explanation
This also allows initializing from props. Creating the store in a useState initializer keeps it stable across renders.