1.0.1 • Published 3 years ago

use-patch-state v1.0.1

Weekly downloads
6
License
ISC
Repository
github
Last release
3 years ago

use-patch-state

npm version Coverage Status Build Status Bundle Phobia

What is this?

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:

patch

import { patch } from 'use-patch-state';

const MyComponent = () => {

    const [state,setState] = useState({ keyA: 1, keyB: 2 });

    const handleSomeAction = () => setState(patch({ keyA: 2 }))

}

usePatchState

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.