TinyBase logoTinyBase β

useSynchronizer

The useSynchronizer hook is used to get a reference to a Synchronizer object from within a Provider component context.

useSynchronizer(id?: string): Synchronizer | undefined
TypeDescription
id?string

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

returnsSynchronizer | undefined

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

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

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

Examples

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

import {Provider, useSynchronizer} from 'tinybase/ui-react';
import React from 'react';
import {createLocalSynchronizer} from 'tinybase/synchronizers/synchronizer-local';
import {createMergeableStore} from 'tinybase';
import {createRoot} from 'react-dom/client';

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

const synchronizer = createLocalSynchronizer(createMergeableStore());
const app = document.createElement('div');
const root = createRoot(app);
root.render(<App synchronizer={synchronizer} />);
console.log(app.innerHTML);
// -> '<span>0</span>'

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

import {Provider, useSynchronizer} from 'tinybase/ui-react';
import React from 'react';
import {createLocalSynchronizer} from 'tinybase/synchronizers/synchronizer-local';
import {createMergeableStore} from 'tinybase';
import {createRoot} from 'react-dom/client';

const App = ({synchronizer}) => (
  <Provider synchronizersById={{petSynchronizer: synchronizer}}>
    <Pane />
  </Provider>
);
const Pane = () => (
  <span>{useSynchronizer('petSynchronizer').getStatus()}</span>
);

const synchronizer = createLocalSynchronizer(createMergeableStore());
const app = document.createElement('div');
const root = createRoot(app);
root.render(<App synchronizer={synchronizer} />);
console.log(app.innerHTML);
// -> '<span>0</span>'

Since

v5.3.0