useStore
The useStore
hook is used to get a reference to a Store
from within a Provider
component context.
useStore(id?: string): Store | undefined
Type | Description | |
---|---|---|
id? | string | An optional |
returns | Store | undefined | A reference to the Store (or `undefined` if not within a Provider context, or if the requested Store does not exist) |
A Provider
component is used to wrap part of an application in a context. It can contain a default Store
(or a set of Store
objects named by Id
) that can be easily accessed without having to be passed down as props through every component.
The useStore
hook lets you either get a reference to the default Store
(when called without an parameter), or one of the Store
objects that are named by Id
(when called with an Id
parameter).
Examples
This example creates a Provider context into which a default Store
is provided. A component within it then uses the useStore
hook to get a reference to the Store
again, without the need to have it passed as a prop.
const App = ({store}) => (
<Provider store={store}>
<Pane />
</Provider>
);
const Pane = () => <span>{useStore().getListenerStats().tables}</span>;
const store = createStore();
const app = document.createElement('div');
ReactDOM.render(<App store={store} />, app);
console.log(app.innerHTML);
// -> '<span>0</span>'
This example creates a Provider context into which a Store
is provided, named by Id
. A component within it then uses the useStore
hook with that Id
to get a reference to the Store
again, without the need to have it passed as a prop.
const App = ({store}) => (
<Provider storesById={{petStore: store}}>
<Pane />
</Provider>
);
const Pane = () => (
<span>{useStore('petStore').getListenerStats().tables}</span>
);
const store = createStore();
const app = document.createElement('div');
ReactDOM.render(<App store={store} />, app);
console.log(app.innerHTML);
// -> '<span>0</span>'