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 |
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 a 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.
import {Provider, useStore} from 'tinybase/ui-react';
import React from 'react';
import {createRoot} from 'react-dom/client';
import {createStore} from 'tinybase';
const App = ({store}) => (
<Provider store={store}>
<Pane />
</Provider>
);
const Pane = () => <span>{useStore().getListenerStats().tables}</span>;
const store = createStore();
const app = document.createElement('div');
createRoot(app).render(<App store={store} />);
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.
import {Provider, useStore} from 'tinybase/ui-react';
import React from 'react';
import {createRoot} from 'react-dom/client';
import {createStore} from 'tinybase';
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');
createRoot(app).render(<App store={store} />);
console.log(app.innerHTML);
// -> '<span>0</span>'
Since
v1.0.0