react-immer
v1.5.3
Published
No nonsense state management with Immer and React hooks
Downloads
150
Readme
react-immer
No nonsense state management with Immer and React hooks
TL;DR
index.js
import React from 'react'
import ReactDOM from 'react'
import { createStore } from 'react-immer'
import Counter from './Counter'
createStore({ count: 1 })
function App() {
return <Counter />
}
const rootElement = document.getElementById('root')
ReactDOM.render(<App />, rootElement)
Counter.js
/* Counter.js */
import React from 'react'
import { useImmer } from 'react-immer'
export default function Counter() {
const [{ count }, produce] = useImmer({ count: state => state.count })
const decrement = draft => {
draft.count -= 1
}
const increment = draft => {
draft.count += 1
}
return (
<div>
<button onClick={() => produce(decrement)}>-</button>
<span>{count}</span>
<button onClick={() => produce(increment)}>+</button>
</div>
)
}
What's cool about react-immer is that if you don't support Hooks yet, you can use it inline and it will work like a render prop. In this case, it takes two arguments, the spec object and the render function.
import { useImmer } from 'react-immer'
// ...
// useImmer(specObj, renderFn)
<div>
{useImmer({ count: state => state.count }, ({ count }, produce) => (
<span>
<button onClick={() => produce(decrement)}>-</button>
<span>{count}</span>
<button onClick={() => produce(increment)}>+</button>
</span>
))}
</div>
Or, if you don't like the syntax, you can always use the Immer component
import { Immer } from 'react-immer'
// ...
<Immer spec={{ count: state => state.count }}>
{({ count }, produce) => (
<span>
<button onClick={() => produce(decrement)}>-</button>
<span>{count}</span>
<button onClick={() => produce(increment)}>+</button>
</span>
)}
</Immer>