Skip to content

Repository files navigation

React Immer Hooks

Easy immutability in React Hooks with Immer.

Note:React Hooks are currently a RFC proposal which may be subject to change. You'll need at least react@16.7.0-alpha.0 to use this feature.

Installation

yarn add react-immer-hooks

Usage

useImmerState(initialState)
import{useImmerState}from'react-immer-hooks'constinitialState={clicks: 0,doubleClicks: 0}constClickCounters=()=>{const[state,setState]=useImmerState(initialState)constonClick=()=>setState(draft=>{draft.clicks++})constonDoubleClick=()=>setState(draft=>{draft.doubleClicks++})return(<><buttononClick={onClick}onDoubleClick={onDoubleClick}>
Clics: {state.clicks}, Double clicks: {state.doubleClicks}</button></>)}
useImmerReducer(reducer, initialState)
import{useImmerReducer}from'react-immer-hooks'constinitialState={count: 0}constreducer=(draft,action)=>{if(action.type==='INCREMENT')draft.count++if(action.type==='DECREMENT')draft.count--if(action.type==='ADD')draft.count+=action.payload}constCounter=()=>{const[state,dispatch]=useImmerReducer(reducer,initialState)return(<>
Count: {state.count}<buttononClick={()=>dispatch({type: 'INCREMENT'})}>
Increment
</button><buttononClick={()=>dispatch({type: 'DECREMENT'})}>
Decrement
</button><buttononClick={()=>dispatch({type: 'ADD',payload: 5})}>
Add 5
</button></>)}

License

MIT License

About

Easy immutability in React Hooks with Immer.

Topics

Resources

Stars

45 stars

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages