Super tiny package that let's you patch the state returned from useState
hook.
React recommends useReducer
for complex (read: key-value) state. And useReducer
is pretty cool. But, often, we don't want to write a reducer, we just want to patch our state object and we find ourselves writing:
setState(existing => ({ ...existing, key: 'value' }))
over and over again.
This package let's you do one of two things:
import { patch } from 'use-patch-state';
const MyComponent = () => {
const [state,setState] = useState({ keyA: 1, keyB: 2 });
const handleSomeAction = () => setState(patch({ keyA: 2 }))
}
import { usePatchState } from 'use-patch-state';
const MyComponent = () => {
const [state,setState] = usePatchState({ keyA: 1, keyB: 2 })
const handleSomeAction = () => setState({ keyA: 1 })
}
The setState
returned from usePatchState
, like dispatch
returned from useReducer
is always referentially the same.