withProvider
import { withProvider } from '@hurum/react'withProvider(StoreDef, Component)
Section titled “withProvider(StoreDef, Component)”A higher-order component that wraps a component with a StoreProvider and automatically creates a new store instance via StoreDef.create(). Each mount of the wrapped component gets its own isolated store.
Signature
Section titled “Signature”function withProvider<P extends object>( def: StoreDefinition, Component: React.ComponentType<P>,): React.ComponentType<P>Parameters
Section titled “Parameters”| Parameter | Type | Description |
|---|---|---|
def | StoreDefinition | The store definition to provide. |
Component | React.ComponentType<P> | The component to wrap. |
Returns
Section titled “Returns”A new component with the same props as the original. Internally renders <StoreProvider of={def} store={...}><Component {...props} /></StoreProvider>.
Import
Section titled “Import”import { withProvider } from '@hurum/react'Example
Section titled “Example”function CartPage() { const cart = useStore(CartStore) const items = cart.use.items() return <div>{items.length} items</div>}
// Wrap with provider -- each mount gets a fresh storeconst CartPageWithProvider = withProvider(CartStore, CartPage)
function App() { return <CartPageWithProvider />}How It Works
Section titled “How It Works”Internally, withProvider uses useState to create the store instance:
// Simplified internal implementationfunction WithProvider(props) { const [store] = useState(() => def.create()) return ( <StoreProvider of={def} store={store}> <WrappedComponent {...props} /> </StoreProvider> )}The store instance is created once via useState’s initializer function and retained for the component’s lifetime.
When to Use
Section titled “When to Use”Use withProvider when:
- You want a fresh, isolated store per component mount.
- You do not need to customize
initialStateordepsat runtime. - You want a concise one-liner instead of manually wiring up
StoreProvider.
Use StoreProvider directly when:
- You need to pass
initialStateordeps. - You need control over the store’s lifecycle (e.g. shared instance, dispose timing).
- Multiple components need to share the same scoped instance.
Display Name
Section titled “Display Name”The wrapped component receives a displayName of withProvider(OriginalName) for easier debugging in React DevTools.
withProviderdoes not accept options forStore.create(). If you need custom initialization, useStoreProviderdirectly.- The store instance survives re-renders but is not shared across different mounts of the wrapped component.
- Like
StoreProvider,withProviderdoes not auto-dispose the store on unmount.