Simple global state management using react hook.
npm i use-simple-store
import createStore from 'use-simple-store'
const { useStore, update } = createStore({ count: 0 })
const increment = () => update(state => {
state.count = state.count + 1
})
const decrement = () => update(state => {
state.count = state.count - 1
})
function App() {
const { count } = useStore()
return (
<div>
<span>{count}</span>
<button onClick={decrement}> - </button>
<button onClick={increment}> + </button>
</div>))
}
Create a store.
Update state by mutate function. (using immer)
const todos = createStore({})
const addTodo = (id, text) =>
todos.update(state => {
state[id] = { id, text, done: false }
})
const deleteTodo = id =>
todos.update(state => {
delete state[id]
})
The update()
does not support promise. If you need an asynchronous update, see the example below: π
async function fetchTodos() {
update(state => {
state.fetching = true
})
const todos = await fetchTodosAsync()
update(state => {
state.fetching = false
state.todos = todos
})
}
Subscribe to state changes.
const { subscribe, update } = createStore({ count: 0 })
subscribe(state => {
console.log(`count: ${state.count}`)
})
update(state => {
state.count++
}) // => count: 1
update(state => {
state.count++
}) // => count: 2
The subscribe()
returns a function to unsubscribe.
const unsubscribe = subscribe(listener)
/* ... */
unsubscribe()
Returns current state.
A react hook to subscribe to store state changes.
Select only the necessary state of the store. When the state of the store is large, its performance is better.
function Todo({ id }) {
const todo = useStore(state => state[id])
const handleClick = () => {
update(state => {
state[id].done = !todo.done
})
}
return <li onClick={handleClick}>{todo.text}</li>)
}
Replace the selector with dependencies
.
const s = useStore(state => state[condition ? 'v1' : 'v2'], [condition])
MIT