1.0.5 • Published 10 months ago
feather-state-react v1.0.5
Feather State React
✨ A feather light state framework for React ✨ 212 bytes minified and gzipped - extends feather-state
Companion frameworks:
Live examples:
Getting started
npm i feather-state-reactUsage
import { useStore } from 'feather-state-react';
const Component = () => {
  const { sync, watch } = useStore(todoStore);
  watch(todoStore, 'todos', (next, prev) => {
    console.log(next, prev);
  });
  return (
    <p>{sync(todoStore.todos[0], 'title')}</p>
  );
};Documentation
store()
store(state) => { state, watch() } | { ...state, watch() };Parameters
state: state value
Return values
state|...state- state valuewatch()- watch for shallow mutations
useStore()
useStore(store) => { sync(), watch() };Parameters
store- return value fromstore()
Return values
sync()- re-render DOM when value changeswatch()- watch for shallow mutations
useStore().sync()
sync(parent, key) => value;Parameters
parent- parent object of watched valuekey- key of watched value
Return values
value- value ofparent[key]
useStore().watch()
watch(parent, key, callback) => unwatch();Parameters
parent- parent object of watched valuekey- key of watched valuecallback()- function called when value changes
Return values
unwatch()- function to unwatch value (Note: values are also automatically unwatched when component unmounts)
Example
todos.ts
import { store } from 'feather-state-react';
export const todoStore = store({
  completedCount: 1,
  todos: [{
    id: 123,
    title: 'Todo 1',
    done: true
  }, {
    id: 456,
    title: 'Todo 2',
    done: false
  }]
});
const updateCompletedCount = () => {
  todoStore.completedCount = todoStore.todos.filter(todo => todo.done).length;
};TodoList.ts
import { useStore } from 'feather-state-react';
import { todoStore, updateCompletedCount } from './todos';
import { TodoItem } from './TodoItem';
const TodoList = () => {
  const { sync, watch } = useStore(todoStore);
  watch(todoStore, 'todos', () => {
    updateCompletedCount();
  });
  return (
    <>
      <ul>
        {sync(todoStore, 'todos').map((todo) => (
          <TodoItem key={todo.id} todo={todo} />
        ))}
      </ul>
      <p>Completed: {sync(todoStore, 'completedCount')}</p>
    </>
  );
};TodoItem.ts
import { useStore } from 'feather-state-react';
import { todoStore, updateCompletedCount } from './todos';
const TodoItem = ({ todo }) => {
  const { watch } = useStore(todoStore);
  watch(todo, 'done', () => {
    updateCompletedCount();
  });
  return (
    <li>{todo.title}</li>
  );
};Roadmap 🚀
- Minified version via CDN
 - Cleaner way of referencing values in render