A minimum and lightweight external store for react

Reactive store – a minimum and lightweight external store for react

Features

  • Inject external data to React hook component
  • Support action to remove or update data
  • Light weight

Installation

yarn add @mcsheffey/reactive-store

or

npm install @mcsheffey/reactive-store

Usage

  • Create a store

import { Store } from '@mcsheffey/reactive-store';

const store = new Store();
const secondStore = new Store();

const keys = {
  inputValue: 'inputValue',
  todoList: 'todoList',
  count: 'count',
};

store.add(keys.inputValue, '');
store.add(keys.count, 0);
secondStore.add(keys.todoList, []);
  • Inject store to Component using StoreInjector
export const App = StoreInjector([store, secondStore], Component);
  • Dispatch an action. There are two kind of action update (update data) or remove (delete data) from store

store.update(keys.count, count + 1);
store.remove(keys.count);
  • Memo data: For some reason you may don’t want to recreate data that extract from store every rerender, this can be achieved by using useCallback hook:

import * as React from 'react';
import { StoreInjector } from '../src';
import { secondStore, keys } from './store';

interface IReturnValue {
  list: () => Array<string>;
}

const Component = () => {
  const todoList: IReturnValue['list'] = React.useCallback(() => {
    return secondStore.get(keys.todoList);
  }, []);
  return (
    <div>
      {todoList().map(val => (
        <p key={val}>{val}</p>
      ))}
    </div>
  );
};

export const TodoList = StoreInjector(secondStore, Component);

Quick start

import { Store, StoreInjector } from '@mcsheffey/reactive-store';

const store = new Store();

const keys = {
  count: 'count',
};
/*Add data to store*/
store.add(keys.count, 0);

const Component = () => {
  /*Get data from store */
  const count: number = store.get(keys.count);
  return (
    <div className="App">
      <button onClick={() => store.update(keys.count, count + 1)}>+</button>
    </div>
  );
};

const App = StoreInjector([store, secondStore], Component);

const rootElement = document.getElementById('root');
ReactDOM.render(<App name="hoa" />, rootElement);

React 18 support

  • See document for React version 18 here

About

GitHub

View Github