1.5.3 • Published 5 years ago

react-immer v1.5.3

Weekly downloads
5
License
MIT
Repository
github
Last release
5 years ago

react-immer

Build Status npm version npm downloads minified size

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>
  )
}

Edit react-immer-tldr

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>
1.5.3

5 years ago

1.5.2

5 years ago

1.5.1

5 years ago

1.5.0

5 years ago

1.4.0

5 years ago

1.3.0

5 years ago

1.2.2

5 years ago

1.2.0

5 years ago

0.1.0

5 years ago

0.0.2

5 years ago

0.0.1

5 years ago

0.0.0

5 years ago