TinyBase logoTinyBase β

useValuesState

The useValuesState hook returns a Values object and a function to set it, following the same pattern as React's useState hook.

useValuesState(storeOrStoreId?: StoreOrStoreId): [Values, (values: Values) => void]
TypeDescription
storeOrStoreId?StoreOrStoreId

The Store to be accessed: omit for the default context Store, provide an Id for a named context Store, or provide an explicit reference.

returns[Values, (values: Values) => void]

An array containing the Values object and a function to set it.

This is a convenience hook that combines the useValues and useSetValuesCallback hooks. It's useful when you need both read and write access to all Values in a single component.

A Provider component is used to wrap part of an application in a context, and it can contain a default Store or a set of Store objects named by Id. The useValuesState hook lets you indicate which Store to use: omit the parameter for the default context Store, provide an Id for a named context Store, or provide a Store explicitly by reference.

Example

This example creates a Store outside the application, which is used in the useValuesState hook by reference. A button updates the Values when clicked.

import {createStore} from 'tinybase';
import React from 'react';
import {createRoot} from 'react-dom/client';
import {useValuesState} from 'tinybase/ui-react';

const store = createStore().setValues({open: true});
const App = () => {
  const [values, setValues] = useValuesState(store);
  return (
    <div>
      {JSON.stringify(values)}
      <button onClick={() => setValues({...values, employees: 3})}>
        Add
      </button>
    </div>
  );
};

const app = document.createElement('div');
const root = createRoot(app);
root.render(<App />);
console.log(app.innerHTML);
// -> '<div>{"open":true}<button>Add</button></div>'

const _button = app.querySelector('button');
// -> _button MouseEvent('click', {bubbles: true})
console.log(app.innerHTML);
// -> '<div>{"open":true,"employees":3}<button>Add</button></div>'

Since

v7.3.0