# use-immer

> Use immer with React hooks

Latest version **0.11.0** (published 2024-12-11) · MIT license · 0 weekly downloads

## Install

```sh
npm install use-immer
pnpm add use-immer
yarn add use-immer
bun add use-immer
```

## Health

**Score 30/100 (F)** — status: maintenance-mode.

Positive: has types; esm support; no vulnerabilities; high quality score.

Warnings: low downloads; pre 1.0.

Negative: stale; low maintenance score; declining downloads.

## Facts

| | |
|---|---|
| Version | 0.11.0 |
| Published | 2024-12-11 |
| First published | 2018-10-25 |
| Weekly downloads | 0 |
| License | MIT |
| TypeScript types | bundled |
| Module format | ESM + CommonJS |
| Dependencies | 0 |
| Unpacked size | 20.5 KB |
| Known vulnerabilities | 0 |
| Install scripts | no |
| GitHub stars | 4548 |
| Author | Michel Weststrate |
| Maintainers | mweststrate |
| Keywords | immer, react, hooks |

## Links

- npm: https://www.npmjs.com/package/use-immer
- Repository: https://github.com/mweststrate/use-immer
- Homepage: https://github.com/mweststrate/use-immer#readme
- Issues: https://github.com/mweststrate/use-immer/issues
- npm.io page: https://npm.io/package/use-immer

## Alternatives

- [mobx-react](https://npm.io/package/mobx-react.md) — 2.8M weekly downloads
- [rc-tree](https://npm.io/package/rc-tree.md) — 2.6M weekly downloads
- [@react-oauth/google](https://npm.io/package/@react-oauth/google.md) — 1.3M weekly downloads
- [@wagmi/connectors](https://npm.io/package/@wagmi/connectors.md) — 877.0K weekly downloads
- [vee-validate](https://npm.io/package/vee-validate.md) — 836.4K weekly downloads

## Recent versions

- 0.11.0 (latest) — 2024-12-11
- 0.10.0 — 2024-06-10
- 0.9.0 — 2023-04-03
- 0.8.1 — 2022-11-19
- 0.8.0 — 2022-11-15
- 0.7.0 — 2022-04-08
- 0.6.0 — 2021-06-24
- 0.5.2 — 2021-05-15
- 0.5.1 — 2021-03-20
- 0.5.0 — 2021-03-20
- 0.4.2 — 2020-11-19
- 0.4.1 — 2020-07-16
- 0.4.0 — 2020-04-06
- 0.3.5 — 2019-10-31
- 0.3.4 — 2019-09-20
- … 13 more at https://npm.io/package/use-immer/versions

## README

# use-immer

A hook to use [immer](https://github.com/mweststrate/immer) as a React [hook](https://reactjs.org/docs/hooks-intro.html) to manipulate state.

# Installation

`npm install immer use-immer`

# API

## useImmer

`useImmer(initialState)` is very similar to [`useState`](https://reactjs.org/docs/hooks-state.html).
The function returns a tuple, the first value of the tuple is the current state, the second is the updater function,
which accepts an [immer producer function](https://immerjs.github.io/immer/produce) or a value as argument.  

### Managing state with immer producer function

When passing a function to the updater, the `draft` argument can be mutated freely, until the producer ends and the changes will be made immutable and become the next state.

Example: https://codesandbox.io/s/l97yrzw8ol

```javascript
import React from "react";
import { useImmer } from "use-immer";


function App() {
  const [person, updatePerson] = useImmer({
    name: "Michel",
    age: 33
  });

  function updateName(name) {
    updatePerson(draft => {
      draft.name = name;
    });
  }

  function becomeOlder() {
    updatePerson(draft => {
      draft.age++;
    });
  }

  return (
    <div className="App">
      <h1>
        Hello {person.name} ({person.age})
      </h1>
      <input
        onChange={e => {
          updateName(e.target.value);
        }}
        value={person.name}
      />
      <br />
      <button onClick={becomeOlder}>Older</button>
    </div>
  );
}
```

(obviously, immer is a little overkill for this example)

### Managing state as simple useState hook
When passing a value to the updater instead of a function, `useImmer` hook behaves the same as useState hook and updates the state with that value.

```javascript
import React from 'react';
import { useImmer } from 'use-immer';

function BirthDayCelebrator(){
  const [age, setAge] = useImmer(20);

  function birthDay(event){
    setAge(age + 1);
    alert(`Happy birthday #${age} Anon! hope you good`);
  }

  return(
    <div>
      <button onClick={birthDay}>It is my birthday</button>
    </div>
  );
}
```

Obviously if you have to deal with immutability it is better option passing a function to the updater instead of a direct value.

## useImmerReducer

Immer powered reducer, based on [`useReducer` hook](https://reactjs.org/docs/hooks-reference.html#usereducer)

Example: https://codesandbox.io/s/2zor1monvp

```javascript
import React from "react";
import { useImmerReducer } from "use-immer";

const initialState = { count: 0 };

function reducer(draft, action) {
  switch (action.type) {
    case "reset":
      return initialState;
    case "increment":
      return void draft.count++;
    case "decrement":
      return void draft.count--;
  }
}

function Counter() {
  const [state, dispatch] = useImmerReducer(reducer, initialState);
  return (
    <>
      Count: {state.count}
      <button onClick={() => dispatch({ type: "reset" })}>Reset</button>
      <button onClick={() => dispatch({ type: "increment" })}>+</button>
      <button onClick={() => dispatch({ type: "decrement" })}>-</button>
    </>
  );
}
```

---
_Source: https://npm.io/package/use-immer · Machine-readable twin of the npm.io package page. Health data is recomputed on every publish._
