TinyBase

The reactive data store for local‑first apps.

README

The reactive data store for local‑first apps.

Modern apps deserve better. Why trade reactive user experiences to be able to use relational data? Why sacrifice store features for bundle size? And why should the cloud do all the work anyway?

TinyBase is a smart new way to structure your local app data:

Tiny by name, tiny by nature, TinyBase only costs 3.5kB - 7.9kB when compressed, and has zero dependencies. And of course it's well tested, fully documented, and open source. Other FAQs?

NEW! v2.2 release


Get started

Try the demos

Read the docs


Set and get tables, rows, and cells.

Creating a Store requires just a simple call to the createStore function. Once you have one, you can easily set Table, Row, or Cell values by their Id. And of course you can easily get the values back out again.

Read more about setting and changing data in The Basics guide.


  1. ```js
  2. const store = createStore()
  3.   .setTable('pets', {fido: {species: 'dog'}})
  4.   .setCell('pets', 'fido', 'color', 'brown');

  5. console.log(store.getRow('pets', 'fido'));
  6. // -> {species: 'dog', color: 'brown'}
  7. ```

Register listeners at any granularity.

The magic starts to happen when you register listeners on a Store, Table, Row, or Cell. They get called when any part of that object changes. You can also use wildcards - useful when you don't know the Id of the objects that might change.

Read more about listeners in the Listening To Stores guide.


  1. ```js
  2. const listenerId = store.addTableListener('pets', () =>
  3.   console.log('changed'),
  4. );

  5. store.setCell('pets', 'fido', 'sold', false);
  6. // -> 'changed'

  7. store.delListener(listenerId);
  8. ```

Call hooks to bind to data.

If you're using React in your application, the optional ui-react module provides hooks to bind to the data in a Store.

More magic! The useCell hook in this example fetches the dog's color. But it also registers a listener on that cell that will fire and re-render the component whenever the value changes.

Basically you simply describe what data you want in your user interface and TinyBase will take care of the whole lifecycle of updating it for you.

Read more about the using hooks in the Using React Hooks guide.


  1. ```jsx
  2. const App1 = () => {
  3.   const color = useCell('pets', 'fido', 'color', store);
  4.   return <>Color: {color}</>;
  5. };

  6. const app = document.createElement('div');
  7. ReactDOM.render(<App1 />, app);
  8. console.log(app.innerHTML);
  9. // -> 'Color: brown'

  10. store.setCell('pets', 'fido', 'color', 'walnut');
  11. console.log(app.innerHTML);
  12. // -> 'Color: walnut'
  13. ```

Use components to make reactive apps.

The react module provides simple React components with bindings that make it easy to create a fully reactive user interface based on a Store.

In this example, the library's RowView component just needs a reference to the Store, the tableId, and the rowId in order to render the contents of that row. An optional cellComponent prop lets you override how you want each Cell rendered. Again, all the listeners and updates are taken care of for you.

The module also includes a context Provider that sets up default for an entire app to use, reducing the need to drill all your props down into your app's hierarchy.

Most of the demos showcase the use of these React hooks and components. Take a look at Todo App v1 (the basics) to see these user interface binding patterns in action.

Read more about the ui-react module in the Building UIs guides.


  1. ```jsx
  2. const MyCellView = (props) => (
  3.   <>
  4.     {props.cellId}: <CellView {...props} />
  5.     <hr />
  6.   </>
  7. );

  8. const App2 = () => (
  9.   <RowView
  10.     store={store}
  11.     tableId="pets"
  12.     rowId="fido"
  13.     cellComponent={MyCellView}
  14.   />
  15. );

  16. ReactDOM.render(<App2 />, app);
  17. console.log(app.innerHTML);
  18. // -> 'species: dog
    color: walnut
    sold: false
    '

  19. store.setCell('pets', 'fido', 'sold', true);
  20. console.log(app.innerHTML);
  21. // -> 'species: dog
    color: walnut
    sold: true
    '

  22. ReactDOM.unmountComponentAtNode(app);
  23. ```

Apply schemas to tables.

By default, a Row can contain any arbitrary Cell. But you can add a schema to a Store to ensure that the values are always what you expect. For example, you can limit their types, and provide defaults. You can also create mutating listeners that can programmatically enforce a schema.

In this example, we set a second Row without the sold Cell in it. The schema ensures it's present with default of false.

Read more about schemas in the Using Schemas guide.


  1. ```js
  2. store.setSchema({
  3.   pets: {
  4.     species: {type: 'string'},
  5.     color: {type: 'string'},
  6.     sold: {type: 'boolean', default: false},
  7.   },
  8. });

  9. store.setRow('pets', 'felix', {species: 'cat'});
  10. console.log(store.getRow('pets', 'felix'));
  11. // -> {species: 'cat', sold: false}

  12. store.delSchema();
  13. ```

Persist data to browser, file, or server.

You can easily persist a Store between browser page reloads or sessions. You can also synchronize it with a web endpoint, or (if you're using TinyBase in an appropriate environment), load and save it to a file.

Read more about persisters in the Persisting Data guide.


  1. ```js
  2. const persister = createSessionPersister(store, 'demo');
  3. await persister.save();

  4. console.log(sessionStorage.getItem('demo'));
  5. // -> '{"pets":{"fido":{"species":"dog","color":"walnut","sold":true},"felix":{"species":"cat","sold":false}}}'

  6. persister.destroy();
  7. sessionStorage.clear();
  8. ```

Build complex queries with TinyQL.

The Queries object lets you query data across tables, with filtering and aggregation - using a SQL-adjacent syntax called TinyQL.

Accessors and listeners let you sort and paginate the results efficiently, making building rich tabular interfaces easier than ever.

In this example, we have two tables: of pets and their owners. They are joined together by the pet's ownerId Cell. We select the pet's species, and the owner's state, and then aggregate the prices for the combinations.

We access the results by descending price, essentially answering the question: "which is the highest-priced species, and in which state?"

Needless to say, the results are reactive too! You can add listeners to queries just as easily as you do to raw tables.

Read more about Queries in the v2.0 Release Notes, the Making Queries guide, and the Car Analysis demo and Movie Database demo.


  1. ```js
  2. store
  3.   .setTable('pets', {
  4.     fido: {species: 'dog', ownerId: '1', price: 5},
  5.     rex: {species: 'dog', ownerId: '2', price: 4},
  6.     felix: {species: 'cat', ownerId: '2', price: 3},
  7.     cujo: {species: 'dog', ownerId: '3', price: 4},
  8.   })
  9.   .setTable('owners', {
  10.     1: {name: 'Alice', state: 'CA'},
  11.     2: {name: 'Bob', state: 'CA'},
  12.     3: {name: 'Carol', state: 'WA'},
  13.   });

  14. const queries = createQueries(store);
  15. queries.setQueryDefinition(
  16.   'prices',
  17.   'pets',
  18.   ({select, join, group}) => {
  19.     select('species');
  20.     select('owners', 'state');
  21.     select('price');
  22.     join('owners', 'ownerId');
  23.     group('price', 'avg').as('avgPrice');
  24.   },
  25. );

  26. queries
  27.   .getResultSortedRowIds('prices', 'avgPrice', true)
  28.   .forEach((rowId) => {
  29.     console.log(queries.getResultRow('prices', rowId));
  30.   });
  31. // -> {species: 'dog', state: 'CA', avgPrice: 4.5}
  32. // -> {species: 'dog', state: 'WA', avgPrice: 4}
  33. // -> {species: 'cat', state: 'CA', avgPrice: 3}

  34. queries.destroy();
  35. ```

Define metrics and aggregations.

A Metrics object makes it easy to keep a running aggregation of Cell values in each Row of a Table. This is useful for counting rows, but also supports averages, ranges of values, or arbitrary aggregations.

In this example, we create a new table of the pet species, and keep a track of which is most expensive. When we add horses to our pet store, the listener detects that the highest price has changed.

Read more about Metrics in the Using Metrics guide.


  1. ```js
  2. store.setTable('species', {
  3.   dog: {price: 5},
  4.   cat: {price: 4},
  5.   worm: {price: 1},
  6. });

  7. const metrics = createMetrics(store);
  8. metrics.setMetricDefinition(
  9.   'highestPrice', // metricId
  10.   'species', //      tableId to aggregate
  11.   'max', //          aggregation
  12.   'price', //        cellId to aggregate
  13. );

  14. console.log(metrics.getMetric('highestPrice'));
  15. // -> 5

  16. metrics.addMetricListener('highestPrice', () =>
  17.   console.log(metrics.getMetric('highestPrice')),
  18. );
  19. store.setCell('species', 'horse', 'price', 20);
  20. // -> 20

  21. metrics.destroy();
  22. ```

Create indexes for fast lookups.

An Indexes object makes it easy to look up all the Row objects that have a certain value in a Cell.

In this example, we create an index on the species Cell values. We can then get the the list of distinct Cell value present for that index (known as 'slices'), and the set of Row objects that match each value.

Indexes objects are reactive too. So you can set listeners on them just as you do for the data in the underlying Store.

Read more about Indexes in the Using Indexes guide.


  1. ```js
  2. const indexes = createIndexes(store);
  3. indexes.setIndexDefinition(
  4.   'bySpecies', // indexId
  5.   'pets', //      tableId to index
  6.   'species', //   cellId to index
  7. );

  8. console.log(indexes.getSliceIds('bySpecies'));
  9. // -> ['dog', 'cat']
  10. console.log(indexes.getSliceRowIds('bySpecies', 'dog'));
  11. // -> ['fido', 'rex', 'cujo']

  12. indexes.addSliceIdsListener('bySpecies', () =>
  13.   console.log(indexes.getSliceIds('bySpecies')),
  14. );
  15. store.setRow('pets', 'lowly', {species: 'worm'});
  16. // -> ['dog', 'cat', 'worm']

  17. indexes.destroy();
  18. ```

Model relationships between tables.

A Relationships object lets you associate a Row in a local Table with the Id of a Row in a remote Table. You can also reference a table to itself to create linked lists.

In this example, the species Cell of the pets Table is used to create a relationship to the species Table, so that we can access the price of a given pet.

Like everything else, you can set listeners on Relationships too.

Read more about Relationships in the Using Relationships guide.


  1. ```js
  2. const relationships = createRelationships(store);
  3. relationships.setRelationshipDefinition(
  4.   'petSpecies', // relationshipId
  5.   'pets', //       local tableId to link from
  6.   'species', //    remote tableId to link to
  7.   'species', //    cellId containing remote key
  8. );

  9. console.log(
  10.   store.getCell(
  11.     relationships.getRemoteTableId('petSpecies'),
  12.     relationships.getRemoteRowId('petSpecies', 'fido'),
  13.     'price',
  14.   ),
  15. );
  16. // -> 5

  17. relationships.destroy();
  18. ```

Set checkpoints for an undo stack.

A Checkpoints object lets you set checkpoints on a Store. Move forward and backward through them to create undo and redo functions.

In this example, we set a checkpoint, then sell one of the pets. Later, the pet is brought back to the shop, and we go back to that checkpoint to revert the store to its previous state.

Read more about Checkpoints in the Using Checkpoints guide.


  1. ```js
  2. const checkpoints = createCheckpoints(store);

  3. store.setCell('pets', 'felix', 'sold', false);
  4. checkpoints.addCheckpoint('pre-sale');

  5. store.setCell('pets', 'felix', 'sold', true);
  6. console.log(store.getCell('pets', 'felix', 'sold'));
  7. // -> true

  8. checkpoints.goBackward();
  9. console.log(store.getCell('pets', 'felix', 'sold'));
  10. // -> false
  11. ```

Generate ORM-like APIs

You can easily create TypeScript .d.ts definitions that model your data and encourage type-safety when reading and writing data - as well as .ts implementations that provide ORM-like methods for your named tables.

Read more about TinyBase's tools and CLI in the Developer Tools guide.


  1. ```js yolo
  2. const tools = createTools(store);
  3. const [dTs, ts] = tools.getStoreApi('shop');

  4. // -- shop.d.ts --
  5. /* Represents the 'pets' Table. */
  6. export type PetsTable = {[rowId: Id]: PetsRow};
  7. /* Represents a Row when getting the content of the 'pets' Table. */
  8. export type PetsRow = {species: string /* ... */};
  9. //...

  10. // -- shop.ts --
  11. export const createShop: typeof createShopDecl = () => {
  12.   //...
  13. };
  14. ```

Did we say tiny?

If you use the basic store module alone, you'll only add a gzipped 3.5kB to your app. You can incrementally add the other modules as you need more functionality, or get it all for 7.9kB.

The ui-react adaptor is just another 3.2kB, the developer tools module is 4.7kB, and everything is fast. Life's easy when you have zero dependencies!

Read more about how TinyBase is structured in the Architecture guide.

 .js.gz.jsdebug.js.d.ts
store3.5kB7.7kB33.2kB127.2kB
metrics1.8kB3.5kB14.7kB29.1kB
indexes1.9kB3.7kB16.5kB33.9kB
relationships1.8kB3.6kB16.6kB42.1kB
queries2.6kB5.5kB24.9kB106.8kB
checkpoints1.4kB2.8kB11.3kB33.0kB
persisters0.8kB1.6kB5.0kB26.8kB
common0.1kB0.1kB0.1kB3.5kB
tinybase (all)7.9kB18.4kB81.0kB0.3kB

Well tested and documented.

TinyBase has 100.0% test coverage, including the code throughout the documentation - even on this page! The guides, demos, and API examples are designed to make it as easy as possible to get up and running.

Read more about how TinyBase is tested in the Unit Testing guide.

 TotalTestedCoverage
Lines1,2491,249100.0%
Statements1,3531,353100.0%
Functions511511100.0%
Branches471471100.0%
Tests2,157
Assertions11,068

Get started

Try the demos

Read the docs


Follow

About

Building TinyBase was an interesting exercise in API design, minification, and documentation. It could not have been built without these great projects and friends, and we hope you enjoy using it!