TinyBase logoTinyBase

useValueListener

The useValueListener hook registers a listener function with a Store that will be called whenever data in a Value changes.

useValueListener(
  valueId: IdOrNull,
  listener: ValueListener,
  listenerDeps?: DependencyList,
  mutator?: boolean,
  storeOrStoreId?: StoreOrStoreId,
): void
TypeDescription
valueIdIdOrNull

The Id of the Value to listen to, or null as a wildcard.

listenerValueListener

The function that will be called whenever data in the Value changes.

listenerDeps?DependencyList

An optional array of dependencies for the listener function, which, if any change, result in the re-registration of the listener. This parameter defaults to an empty array.

mutator?boolean

An optional boolean that indicates that the listener mutates Store data.

storeOrStoreId?StoreOrStoreId

The Store to register the listener with: omit for the default context Store, provide an Id for a named context Store, or provide an explicit reference.

returnsvoid

This has no return value.

This hook is useful for situations where a component needs to register its own specific listener to do more than simply tracking the value (which is more easily done with the useValue hook).

You can either listen to a single Value (by specifying its Id as the method's first parameter) or changes to any Value (by providing a null wildcard).

Unlike the addValueListener method, which returns a listener Id and requires you to remove it manually, the useValueListener hook manages this lifecycle for you: when the listener changes (per its listenerDeps dependencies) or the component unmounts, the listener on the underlying Store will be deleted.

Example

This example uses the useValueListener hook to create a listener that is scoped to a single component. When the component is unmounted, the listener is removed from the Store.

import {Provider, useValueListener} 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 = () => {
  useValueListener('open', () => console.log('Value changed'));
  return <span>App</span>;
};

const store = createStore().setValues({open: true});
const app = document.createElement('div');
const root = createRoot(app);
root.render(<App store={store} />);
console.log(store.getListenerStats().value);
// -> 1

store.setValue('open', false);
// -> 'Value changed'

root.unmount();
console.log(store.getListenerStats().value);
// -> 0

Since

v3.0.0