Provider for Isolated State
Create component-scoped stores with perfect isolation using React Context
Why Use Providers?
Providers create isolated store instances perfect for components that need their own state without affecting other instances. Think modals, tabs, or any component that appears multiple times.
Creating a Provider
Use createProvider
to create isolated, component-scoped stores:
const [Provider, useFindStore, storeActions] = createProvider(initialState);
For example, you can create a provider for a scoped store with actions
like this:
const [CounterStoreProvider, useFindCounterStore, storeActions] =
createProvider({
count: 0,
increment() {
// Access store actions within the provider scope
const state = storeActions.getState();
storeActions.setState({
...state,
count: state.count + 1,
});
},
});
Notes:
- The
storeActions
can ONLY be used within the initial state'sactions
function - You can use
useFindStore
to get the store instance from the provider - It's very similar to Vue's
provide
/inject
pattern
Multiple Isolated Instances
You can pass different initial state to different store providers, they are isolated from each other.
function App() {
return (
<div className="app">
<h1>Independent Counters</h1>
{/* Each counter is completely isolated */}
<CounterProvider initialState={{ count: 100 }}>
<Counter title="Counter A" />
</CounterProvider>
<CounterProvider initialState={{ count: 200 }}>
<Counter title="Counter B" />
</CounterProvider>
</div>
);
}
Using the Store
Access the provider's store instance within the component tree:
function Counter({ title }) {
// Get the isolated store instance
const counterStore = useCounterStore();
// Use like any other store
const { count } = useStoreValue(counterStore);
return (
<div className="counter">
<h2>{title}</h2>
<p>Count: {count}</p>
<button onClick={counterStore.value.increment}>Increment</button>
</div>
);
}
Perfect isolation made simple. Each provider creates its own universe! 🌟