Skip to content

zuze-lab/use-patch-state

Repository files navigation

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.

About

Super tiny function/react-hook to patch state

Resources

Stars

Watchers

Forks

Packages

No packages published