Skip to Content

useImmer

A custom React hook that integrates Immer for immutable state management

useImmer provides an Immer-like mutation workflow without adding the Immer dependency. The hook clones the previous value with structuredClone, passes the clone to an updater, and stores the updated clone.

useImmerReducer uses the same model for reducer-style updates.

Installation

CLI

npx shadcn add https://ui.tiesen.id.vn/r/use-immer.json

Manual

Copy and paste the following code into your project.

import { useCallback, useRef, useState } from 'react'export function useImmer<T>(  initialValue: T): [T, (updater: (draft: T) => void) => void] {  const [state, setState] = useState(initialValue)  const updateState = useCallback((updater: (draft: T) => void) => {    setState((prevState) => {      const draft = structuredClone(prevState)      updater(draft)      return draft    })  }, [])  return [state, updateState]}export function useImmerReducer<TValue, TAction>(  reducer: (draft: TValue, action: TAction) => void,  initialValue: TValue): [TValue, (action: TAction) => void] {  const [state, setState] = useState(initialValue)  const reducerRef = useRef(reducer)  const dispatch = useCallback((action: TAction) => {    setState((prev) => {      const draft = structuredClone(prev)      reducerRef.current(draft as TValue, action)      return draft    })  }, [])  return [state, dispatch]}

Usage

import { useImmer } from '@/hooks/use-immer'

export function Counter() {
  const [state, updateState] = useImmer({
    count: 0,
    history: [] as number[],
  })

  return (
    <button
      onClick={() =>
        updateState((draft) => {
          draft.count += 1
          draft.history.push(draft.count)
        })
      }
    >
      {state.count}
    </button>
  )
}

Nested data

Because structuredClone creates a deep clone of the previous state, nested properties can be updated with normal assignment syntax.

updateState((draft) => {
  draft.profile.name = 'Tiến'
  draft.preferences.darkMode = true
})

The state must be cloneable by structuredClone.

useImmerReducer

Use the reducer helper when updates are better expressed as actions:

const [state, dispatch] = useImmerReducer(
  (draft, action: 'increment' | 'decrement') => {
    if (action === 'increment') draft.count += 1
    else draft.count -= 1
  },
  { count: 0 }
)

API Reference

useImmer

function useImmer<T>(
  initialValue: T
): [T, (updater: (draft: T) => void) => void]

useImmerReducer

function useImmerReducer<TValue, TAction>(
  reducer: (draft: TValue, action: TAction) => void,
  initialValue: TValue
): [TValue, (action: TAction) => void]

Both helpers use structuredClone rather than the Immer package. Methods/classes or values that structuredClone cannot serialize are therefore not suitable as state values for these hooks.

On this page