✨ A feather light state framework for React ✨ 212 bytes minified and gzipped - extends feather-state
Live examples:
Companion frameworks:
- State - feather-state
- Render - feather-render
npm i feather-state-react
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>
);
};
store(state) => { state, watch() } | { ...state, watch() };
-
state
: state value
-
state
|...state
- state value -
watch()
- watch for shallow mutations
useStore(store) => { sync(), watch() };
-
store
- return value fromstore()
-
sync()
- re-render DOM when value changes -
watch()
- watch for shallow mutations
sync(parent, key) => value;
-
parent
- parent object of watched value -
key
- key of watched value
-
value
- value ofparent[key]
watch(parent, key, callback) => unwatch();
-
parent
- parent object of watched value -
key
- key of watched value -
callback()
- function called when value changes
-
unwatch()
- function to unwatch value (Note: values are also automatically unwatched when component unmounts)
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;
};
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>
</>
);
};
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>
);
};
- Minified version via CDN
- Cleaner way of referencing values in render