npm i picostate --save
Event-based immutable state management.
- 400 bytes
- familiar event based interface
- only fires listeners for changed values
- emits state updates only when requested
- integrates seamlessly with React
Create a store:
import createStore from "picostate";
const store = createStore({
a: 0,
b: false
});
Safely access state:
store.state; // { a: 0, b: false }
Register a listener for any state changes:
store.listen(state => console.log(state));
Register a listener only for changes to an array of props, in this case b
:
store.listen(["b"], state => console.log(state.b));
Update state:
const emit = store.hydrate({ a: 1 });
Fire registered listeners:
emit(); // { a: 1, b: false }
Update state and fire listeners:
store.hydrate({ b: true })(); // { a: 1, b: true }, true
Update state using the previous state:
store.hydrate(state => ({ a: state.a + 1 }))(); // { a: 2, b: true }
const removeListener = store.listen(state => console.log(state));
store.hydrate({ a: 1 })(); // { a: 1, b: true }
removeListener();
store.hydrate({ a: 2 })(); // no listener fired
store.state; // { a: 2, b: true }
Reset to initial state:
store.hydrate();
store.state; // { a: 0, b: false }
MIT License © Eric Bailey