Convert Figma logo to code with AI

immerjs logoimmer

Create the next immutable state by mutating the current one

27,641
850
27,641
50

Top Related Projects

The official, opinionated, batteries-included toolset for efficient Redux development

27,458

Simple, scalable state management.

46,119

🐻 Bear necessities for state management in React

26,868

Actor-based state management & orchestration for complex app logic.

Quick Overview

Immer is a JavaScript library that simplifies immutable state management. It allows you to work with immutable data structures as if they were mutable, while automatically producing the next immutable state. This approach significantly reduces boilerplate code and makes state updates more intuitive.

Pros

  • Simplifies working with immutable data structures
  • Reduces boilerplate code in state management
  • Integrates well with React and Redux
  • Provides excellent TypeScript support

Cons

  • Adds a small runtime overhead
  • May have a learning curve for developers new to immutability concepts
  • Can lead to performance issues if overused with large data structures

Code Examples

  1. Basic usage:
import produce from 'immer';

const baseState = [
  { title: 'Learn TypeScript', done: true },
  { title: 'Try Immer', done: false }
];

const nextState = produce(baseState, draft => {
  draft[1].done = true;
  draft.push({ title: 'Tweet about it', done: false });
});
  1. Using with React useState:
import { useImmer } from 'use-immer';

function TodoList() {
  const [todos, updateTodos] = useImmer([
    { id: 1, title: 'Learn Immer', done: false }
  ]);

  const toggleTodo = id => {
    updateTodos(draft => {
      const todo = draft.find(t => t.id === id);
      todo.done = !todo.done;
    });
  };

  // ... render logic
}
  1. Creating your own produce function:
import { produce, enablePatches } from 'immer';

enablePatches();

const produceWithPatches = produce.bind(null, (state, producer) => {
  let patches, inversePatches;
  [state, patches, inversePatches] = produce(
    state,
    producer,
    (p, ip) => { patches = p; inversePatches = ip; }
  );
  return [state, patches, inversePatches];
});

Getting Started

To start using Immer in your project:

  1. Install Immer:

    npm install immer
    
  2. Import and use in your code:

    import produce from 'immer';
    
    const baseState = { count: 0 };
    const nextState = produce(baseState, draft => {
      draft.count += 1;
    });
    
    console.log(nextState); // { count: 1 }
    console.log(baseState === nextState); // false
    

That's it! You can now start using Immer to simplify your immutable state management.

Competitor Comparisons

The official, opinionated, batteries-included toolset for efficient Redux development

Pros of Redux Toolkit

  • Provides a complete state management solution with built-in tools and utilities
  • Includes RTK Query for efficient API data fetching and caching
  • Offers a more opinionated structure, reducing boilerplate code

Cons of Redux Toolkit

  • Steeper learning curve due to its comprehensive nature
  • Potentially overkill for smaller applications or simpler state management needs
  • More complex setup process compared to Immer's simplicity

Code Comparison

Redux Toolkit:

import { createSlice } from '@reduxjs/toolkit'

const counterSlice = createSlice({
  name: 'counter',
  initialState: 0,
  reducers: {
    increment: state => state + 1,
  },
})

Immer:

import produce from 'immer'

const baseState = [
  { title: 'Learn TypeScript', done: true },
  { title: 'Try Immer', done: false }
]

const nextState = produce(baseState, draft => {
  draft[1].done = true
})

Redux Toolkit uses Immer under the hood, allowing for direct state mutations in reducers. Immer, on the other hand, focuses solely on providing immutable state updates with a mutable API. Redux Toolkit offers a more comprehensive solution for state management, while Immer is a lightweight library for simplifying immutable updates in any JavaScript application.

27,458

Simple, scalable state management.

Pros of MobX

  • More comprehensive state management solution with reactive programming concepts
  • Automatic tracking of dependencies and re-rendering
  • Suitable for complex applications with intricate state relationships

Cons of MobX

  • Steeper learning curve due to its reactive programming paradigm
  • More opinionated and can lead to tight coupling if not used carefully
  • Potential performance overhead for large-scale applications

Code Comparison

MobX:

import { makeObservable, observable, action } from "mobx";

class TodoStore {
  todos = [];

  constructor() {
    makeObservable(this, {
      todos: observable,
      addTodo: action
    });
  }

  addTodo(text) {
    this.todos.push({ text, completed: false });
  }
}

Immer:

import produce from "immer";

const todoStore = {
  todos: [],
  addTodo: (text) => produce(todoStore, (draft) => {
    draft.todos.push({ text, completed: false });
  })
};

MobX offers a more comprehensive solution with built-in reactivity, while Immer focuses on simplifying immutable state updates. MobX is better suited for complex applications, whereas Immer is more lightweight and easier to integrate into existing projects. The choice between them depends on the specific needs of your application and your preferred state management approach.

46,119

🐻 Bear necessities for state management in React

Pros of Zustand

  • Simpler API with less boilerplate code
  • Built-in support for middleware and devtools
  • Smaller bundle size and better performance

Cons of Zustand

  • Less powerful immutability guarantees
  • Fewer built-in utilities for complex state updates
  • Steeper learning curve for advanced usage

Code Comparison

Zustand:

import create from 'zustand'

const useStore = create(set => ({
  count: 0,
  increment: () => set(state => ({ count: state.count + 1 })),
}))

Immer:

import produce from 'immer'

const baseState = { count: 0 }
const nextState = produce(baseState, draft => {
  draft.count++
})

Zustand focuses on creating a simple, hook-based state management solution, while Immer specializes in providing immutable state updates with a mutable API. Zustand offers a more streamlined approach to state management, making it easier to set up and use for small to medium-sized applications. Immer, on the other hand, excels at handling complex state updates in a more intuitive way, especially when dealing with deeply nested objects. While Zustand can be used as a standalone solution, Immer is often integrated into other state management libraries to enhance their immutability features.

26,868

Actor-based state management & orchestration for complex app logic.

Pros of XState

  • Provides a robust state management solution based on finite state machines and statecharts
  • Offers visual editing and debugging tools through the XState Visualizer
  • Supports complex state transitions and hierarchical states

Cons of XState

  • Steeper learning curve due to its state machine concepts
  • Can be overkill for simple state management needs
  • Requires more boilerplate code compared to simpler solutions

Code Comparison

XState:

import { createMachine, interpret } from 'xstate';

const toggleMachine = createMachine({
  id: 'toggle',
  initial: 'inactive',
  states: {
    inactive: { on: { TOGGLE: 'active' } },
    active: { on: { TOGGLE: 'inactive' } }
  }
});

Immer:

import produce from 'immer';

const toggleState = (state) => produce(state, (draft) => {
  draft.active = !draft.active;
});

Key Differences

  • XState focuses on state machines and complex state management
  • Immer specializes in immutable state updates with a mutable API
  • XState provides more structure for larger applications
  • Immer offers a simpler API for basic state mutations

Use Cases

  • XState: Complex workflows, multi-step forms, game state management
  • Immer: Redux reducers, React state updates, simple data mutations

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

Immer

npm Build Status Coverage Status code style: prettier OpenCollective OpenCollective Gitpod Ready-to-Code

Create the next immutable state tree by simply modifying the current tree

Winner of the "Breakthrough of the year" React open source award and "Most impactful contribution" JavaScript open source award in 2019

Contribute using one-click online setup

You can use Gitpod (a free online VS Code like IDE) for contributing online. With a single click it will launch a workspace and automatically:

  • clone the immer repo.
  • install the dependencies.
  • run yarn run start.

so that you can start coding straight away.

Open in Gitpod

Documentation

The documentation of this package is hosted at https://immerjs.github.io/immer/

Support

Did Immer make a difference to your project? Join the open collective at https://opencollective.com/immer!

Release notes

https://github.com/immerjs/immer/releases

NPM DownloadsLast 30 Days