use-prop-change
use-prop-change
React hook for simplifying setState
decomposition into smaller setters for particular state parts.
It can usefull when you need:
- transfer control over part of the state to another component;
- set or change some data in nested state tree;
- simplify working with forms without big library;
Install
$ npm install use-prop-change
or
$ yarn add use-prop-change
Usage Example
;; ; // this component responsible for friends field const forInput = ; const defaultPerson = name: "Dasha" age: "23" friends: /* whatever here */ ; const PersonForm = { const person setPerson = ; const handlePersonProp = ; return <form onSubmit=/* do something */> <input value=personname onChange= /> <input value=personage onChange= /> <Friends friends=personfriends onFriendsChange= /> </form> ;};
How it works?
use-prop-change
use ramda lens under the hood.
But you don't need understand them to use this hook.
For example above we can replace
const handlePersonProp = ;
to
const handlePersonProp = { ;};
But note, handlePersonProp
returned from usePropChange
more powerfull:
- if first argument is number, new state will be an Array
- if first argument is string, new state will be an Object
- if first argument is array, state will be changed on this path
- 2 arguments (name and value) can be passed together, to just make changes once
You can see all this on example