gitmyhub

use-immer

TypeScript ★ 4.5k updated 1y ago

Use immer to drive state with a React hooks

use-immer connects the Immer library to React hooks, letting you update component state by writing simple, direct-looking code instead of manually copying objects. It wraps useState and useReducer with Immer's draft-based approach, so React's immutability rules are handled automatically behind the s

TypeScriptReactImmernpmsetup: easycomplexity 2/5

use-immer is a small library that connects the immer library to React's built-in state management system. To understand what it does, a little background helps. React is a popular JavaScript framework for building user interfaces, and it manages data through something called state. A rule in React is that you should never directly modify state data; instead, you create a new copy of the data with your changes applied. Immer is a library that makes this feel simpler: you write code that looks like you are directly changing the data, and immer automatically produces the correct new copy behind the scenes. use-immer brings that pattern into React hooks, which are the standard way React components manage state today.

The library provides two main tools. The first is useImmer, which works almost identically to React's built-in useState hook. You call it with a starting value, and it gives back the current state and an update function. The difference is that the update function accepts an immer producer: a function where you can freely modify a draft copy of the state, and immer converts those mutations into an immutable update. If you pass a plain value instead of a function, it behaves exactly like useState.

The second tool is useImmerReducer, which mirrors React's useReducer hook. Reducers are a pattern for managing more complex state changes through named actions (like increment, decrement, or reset). With useImmerReducer, your reducer function receives a mutable draft of the state rather than requiring you to write spread operators and object copies manually.

The README is short and focused on code examples rather than prose explanations. Installation requires adding both immer and use-immer as npm packages. The library is tiny in scope: it does not manage side effects, server data, or global state across components. It is specifically a quality-of-life layer for the common task of updating local component state.

Where it fits