1.0.2 • Published 4 years ago
minact v1.0.2
Minact
A simple react state management library without a provider
Demo
https://codesandbox.io/s/minact-demo-b3f6nd
Installation
npm install minact
# or
# yarn add minactUsage
Create a store
import { createStore } from "minact";
export const { useSelector, useDispatch } = createStore(
  { count: 0 },
  (set, get) => ({
    increase: (amount) => set({ count: get().count + (amount || 1) }),
  })
);Use the hooks inside your components
const View = () => {
  const count = useSelector((state) => state.count);
  return <div>Count: {count}</div>;
};
const Controls = () => {
  const increase = useDispatch((reducers) => reducers.increase);
  return <button onClick={() => increase()}>Increase</button>;
};Async actions
Just call the set function to update the store, async functions don't matter.
createStore({ data: null }, (set, get) => ({
  update: async (url) => {
    const res = await fetch(url);
    const data = await res.json();
    set({ data });
  },
}));Multiple selectors
const App = () => {
  const { count, user } = useSelector((state) => ({
    count: state.count,
    user: state.user,
  }));
  // or
  const [ count, user ] = useSelector((state) => [
    count: state.count,
    user: state.user,
  ]);
  // useDispatch also works
  const { increase, decrease } = useDispatch((reducers) => ({
    increase: reducers.increase,
    decrease: reducers.decrease,
  }));
  // or
  const [ increase, decrease ] = useDispatch((reducers) => [
    increase: reducers.increase,
    decrease: reducers.decrease,
  ]);
};Usage outside of react component
const store = createStore({ count: 0 }, (set, get) => ({
  increase: () => set({ count: get().count + 1 }),
}));
// Subscribe to store changes and log the state
const unsubscribe = store.subscribe(() => console.log(store.get()));
// Unsubscribe from changes
unsubscribe();Scales very well
src
│── store
│   │── user-store.js
│   │── count-store.js
│   │── any-store.jsYou can create as many store as you want, they will work independently from each other