Dark Mode

Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

sin/react-immer-hooks

Folders and files

NameName
Last commit message
Last commit date

Latest commit

History

1 Commit

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)
{ const [ state, setState ] = useImmerState(initialState) const onClick = () => setState(draft => { draft.clicks++ }) const onDoubleClick = () => setState(draft => { draft.doubleClicks++ }) return ( <> ) }">import { useImmerState } from 'react-immer-hooks'

const initialState = {
clicks: 0,
doubleClicks: 0
}

const ClickCounters = () => {
const [ state, setState ] = useImmerState(initialState)

const onClick = () => setState(draft => { draft.clicks++ })
const onDoubleClick = () => setState(draft => { draft.doubleClicks++ })

return (
<>
<button onClick={onClick} onDoubleClick={onDoubleClick}>
Clics: {state.clicks}, Double clicks: {state.doubleClicks}
button>
>
)
}
useImmerReducer(reducer, initialState)
{ if (action.type === 'INCREMENT') draft.count++ if (action.type === 'DECREMENT') draft.count-- if (action.type === 'ADD') draft.count += action.payload } const Counter = () => { const [ state, dispatch ] = useImmerReducer(reducer, initialState) return ( <> Count: {state.count} ) }">import { useImmerReducer } from 'react-immer-hooks'

const initialState = {
count: 0
}

const reducer = (draft, action) => {
if (action.type === 'INCREMENT') draft.count++
if (action.type === 'DECREMENT') draft.count--
if (action.type === 'ADD') draft.count += action.payload
}

const Counter = () => {
const [ state, dispatch ] = useImmerReducer(reducer, initialState)

return (
<>
Count: {state.count}
<button onClick={() => dispatch({ type: 'INCREMENT'})}>
Increment
button>
<button onClick={() => dispatch({ type: 'DECREMENT'})}>
Decrement
button>
<button onClick={() => dispatch({ type: 'ADD', payload: 5})}>
Add 5
button>
>
)
}

License

MIT License

About

Easy immutability in React Hooks with Immer.

Topics

Resources

Readme

License

MIT license

Stars

Watchers

Forks

Releases

No releases published

Packages

Contributors