Custom context store access
A component tree uses a custom React context and needs a hook that reads its Provider-managed Redux store.
Redux Toolkit · Hook
createStoreHook creates a useStore-style hook bound to a specified React context. Use it when custom React-Redux hooks must read the store from a Provider configured with that context.
createStoreHook builds a useStore-style hook for a chosen React context. Components using the returned hook retrieve the Redux store supplied through a Provider configured with that same context.
createStoreHook(context)| Name | Type | Description |
|---|---|---|
context | React.Context<ReactReduxContextValue | null> | A React context used by the generated hook to locate the Provider's store. |
A custom useStore hook bound to the supplied React context.
import * as React from 'react'
import { Provider, createStoreHook } from 'react-redux'
const MyContext = React.createContext(null)
const useMyStore = createStoreHook(MyContext)
const store = { getState: () => ({ count: 0 }) }
function Counter() {
const currentStore = useMyStore()
return <output>{currentStore === store ? 'connected' : 'disconnected'}</output>
}
export function App() {
return (
<Provider context={MyContext} store={store}>
<Counter />
</Provider>
)
}Creates a store hook bound to a custom React context, then reads the Provider's store from a descendant component.
A component tree uses a custom React context and needs a hook that reads its Provider-managed Redux store.
An RTK Query API must use React-Redux hooks associated with a non-default context.
Separate Providers or store integrations require hook factories tied to distinct contexts.
createStoreHook is a factory that returns a store-reading hook associated with a supplied React context. The returned hook lets components retrieve the store from a Provider using that context.
Follow-up: Why use it with a custom context? It allows separate React-Redux hook sets to target different stores or independently configured Providers.
Pass the custom context to createStoreHook, export the resulting hook, and configure Provider with the same context. Descendant components can then call the generated hook to obtain the Provider's store.
Follow-up: What breaks if the contexts differ? The hook looks up a different context, so it will not read the store supplied through the intended Provider.
It is useful when configuring React-Redux hooks for a custom context, including an RTK Query API created with customized React hooks. The factory is used alongside createDispatchHook and createSelectorHook.
Follow-up: How can the complete custom hook set be configured? Supply hooks created from the same context to the hooks configuration used when building the API.
createDispatchHookcreateSelectorHookuseStoreProviderbuildCreateApireactHooksModule