TinyBase logoTinyBase β

usePersister

The usePersister hook is used to get a reference to a Persister object from within a Provider component context.

usePersister(id?: string): AnyPersister | undefined
TypeDescription
id?string

An optional Id for accessing a Persister object that was named with an Id in the Provider.

returnsAnyPersister | undefined

A reference to the Persister object (or undefined if not within a Provider context, or if the requested Persister object does not exist).

A Provider component is used to wrap part of an application in a context. It can contain a default Persister object (or a set of Persister objects named by Id) that can be easily accessed without having to be passed down as props through every component.

The usePersister hook lets you either get a reference to the default Persister object (when called without a parameter), or one of the Persister objects that are named by Id (when called with an Id parameter).

Examples

This example creates a Provider context into which a default Persister object is provided. A component within it then uses the usePersister hook to get a reference to the Persister object again, without the need to have it passed as a prop.

import {Provider, usePersister} from 'tinybase/ui-react';
import React from 'react';
import {createRoot} from 'react-dom/client';
import {createSessionPersister} from 'tinybase/persisters/persister-browser';
import {createStore} from 'tinybase';

const App = ({persister}) => (
  <Provider persister={persister}>
    <Pane />
  </Provider>
);
const Pane = () => <span>{usePersister().getStatus()}</span>;

const persister = createSessionPersister(createStore(), 'pets');
const app = document.createElement('div');
const root = createRoot(app);
root.render(<App persister={persister} />);
console.log(app.innerHTML);
// -> '<span>0</span>'

This example creates a Provider context into which a Persister object is provided, named by Id. A component within it then uses the usePersister hook with that Id to get a reference to the Persister object again, without the need to have it passed as a prop.

import {Provider, usePersister} from 'tinybase/ui-react';
import React from 'react';
import {createRoot} from 'react-dom/client';
import {createSessionPersister} from 'tinybase/persisters/persister-browser';
import {createStore} from 'tinybase';

const App = ({persister}) => (
  <Provider persistersById={{petPersister: persister}}>
    <Pane />
  </Provider>
);
const Pane = () => <span>{usePersister('petPersister').getStatus()}</span>;

const persister = createSessionPersister(createStore(), 'pets');
const app = document.createElement('div');
const root = createRoot(app);
root.render(<App persister={persister} />);
console.log(app.innerHTML);
// -> '<span>0</span>'

Since

v5.3.0