TinyBase logoTinyBase β

useCellState

The useCellState hook returns a Cell from a Store and a callback to set it, following the common React useState convention.

useCellState(
  tableId: string,
  rowId: string,
  cellId: string,
  storeOrStoreId?: StoreOrStoreId,
): [CellOrUndefined, (cell: Cell) => void]
TypeDescription
tableIdstring

The Id of the Table in the Store.

rowIdstring

The Id of the Row in the Table.

cellIdstring

The Id of the Cell in the Row.

storeOrStoreId?StoreOrStoreId

The Store to get data from: omit for the default context Store, provide an Id for a named context Store, or provide an explicit reference.

returns[CellOrUndefined, (cell: Cell) => void]

A tuple containing the current Cell and a setter callback that can be called with a new Cell value.

This hook is useful for creating components that read and write a Cell in a single line, similar to how you would use React's useState hook.

The component this is used in will re-render when the Cell changes.

Example

This example creates a Store outside the application, which is used in the useCellState hook by reference.

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

const store = createStore().setCell('pets', 'fido', 'visits', 0);
const App = () => {
  const [visits, setVisits] = useCellState(
    'pets',
    'fido',
    'visits',
    store,
  );
  return (
    <span>
      Visits: {visits}
      <button onClick={() => setVisits(visits + 1)}>Visit</button>
    </span>
  );
};

const app = document.createElement('div');
const root = createRoot(app);
root.render(<App />);
console.log(app.innerHTML);
// -> '<span>Visits: 0<button>Visit</button></span>'

const _button = app.querySelector('button');
// -> _button MouseEvent('click', {bubbles: true})
console.log(app.innerHTML);
// -> '<span>Visits: 1<button>Visit</button></span>'

root.unmount();

Since

v7.3.0