<!-- mobian-agent-page publisher="dailydev" canonical="https://daily.dev/posts/setimmutable-immutable-updates-without-wrestling-the-spread-operator-cxr5qrigc" -->

---
title: setimmutable: immutable updates without wrestling the...
description: setimmutable is a small npm library offering an immutable alternative to lodash.set, designed for deeply nested state updates without hand-writing spread...
canonical: https://daily.dev/posts/setimmutable-immutable-updates-without-wrestling-the-spread-operator-cxr5qrigc
twitter:card: summary_large_image
twitter:site: @dailydotdev
og:type: website
og:site_name: daily.dev
og:title: setimmutable: immutable updates without wrestling the spread operator | daily.dev
og:description: setimmutable is a small npm library offering an immutable alternative to lodash.set, designed for deeply nested state updates without hand-writing spread...
og:url: https://daily.dev/posts/setimmutable-immutable-updates-without-wrestling-the-spread-operator-cxr5qrigc
og:image: https://api.daily.dev/og/posts/CXR5qrIgC.png
og:image:alt: setimmutable: immutable updates without wrestling the spread operator
og:image:width: 1200
og:image:height: 630
og:locale: en
---

> ## Documentation Index
> Fetch the complete documentation index at: https://daily.dev/llms.txt
> Use this file to discover all available pages before exploring further.

# setimmutable: immutable updates without wrestling the spread operator

**[Jonathan Delgado](https://daily.dev/sources/ccmfsskv5iewk1pmun3oj)** · [@jonathandelgado](https://daily.dev/jonathandelgado) · 3 min read · 0 upvotes · 0 comments

## Summary

setimmutable is a small npm library offering an immutable alternative to lodash.set, designed for deeply nested state updates without hand-writing spread operators. It rebuilds only the object tree path being changed while preserving reference equality for untouched branches, which matters for Redux selectors and React.memo. The API includes set(), clone(), and map() for batched updates, plus support for custom cloning of class instances. Unlike Object.freeze, which only freezes the first level of an object, setimmutable's structural-sharing approach protects the whole tree regardless of freezing.

## Content

If you've ever written a Redux reducer for state nested three or four levels deep, you know the pain:

```
const nextState = {
  ...state,
  user: {
    ...state.user,
    address: {
      ...state.user.address,
      city: 'Santiago',
    },
  },
};
```

Every extra level of nesting adds another `...spread`, and forgetting just one is enough to mutate state by accident and break the reference equality that React/Redux rely on to decide whether to re-render. **[setimmutable](https://www.npmjs.com/package/setimmutable)** solves exactly that problem: it's an alternative to `lodash.set` built for working with immutable objects.

## What makes it different?

`lodash.set` is fast and direct, but it mutates the original object in place. That's a problem in any architecture that depends on reference comparisons — Redux, frozen state trees, memoization with `React.memo`, and so on.

`setimmutable` instead rebuilds the object tree only up to the node being changed, and **preserves the original reference of every branch that wasn't touched**:

```
import { set } from 'setimmutable';

const object = { a: { b: { c: 1 }, other: {} } };
const next = set(object, 'a.b.c', 2);

next !== object;                  // true, new root object
next.a.other === object.a.other;  // true, untouched branch: same reference
```

That's what makes it useful in Redux: selectors pointing at parts of the state that didn't change keep returning the same reference, so memoized components don't re-render unnecessarily.

## The API in a few lines

- `set(object, path, value, [customClone])` — performs the immutable update. `path` accepts both dot-notation strings (`'a.b.c'`) and arrays (`['a', 'b', 'c']`).
- `clone(value)` — the per-node clone function `set` uses internally; it creates an empty instance of the value's constructor without copying its properties.
- `map(object, mapping)` — batches multiple `set` calls into one, with three syntaxes: an array of `[path, value]` pairs, callback functions that call `set()`, or literal builders with `set()` calls inline.

```
const object = {};
set(object, '0.1.2', 'a');
// => { '0': { '1': { '2': 'a' } } }
```

### Custom cloning

When your state tree holds your own classes — not just plain objects — you can tell `setimmutable` how to clone them:

```
function customClone(objValue, key) {
  if (objValue.constructor === MyClass) {
    return MyClass.parse(objValue);
  }
  return clone(objValue);
}

set(state, 'session.user', newUser, customClone);
```

## Why "shallow freeze" matters

One detail that tends to surprise people: `Object.freeze` only freezes the first level of an object. If you freeze `state` but not `state.user`, anyone can still mutate `state.user` without anyone noticing. `setimmutable` doesn't rely on `freeze` at all — immutability comes from its structural-sharing strategy, so the whole tree is protected regardless of whether you froze it.

## Installation

```
npm install --save setimmutable
```

It ships as both ESM and CommonJS, with subpaths for specific functions like `setimmutable/map` and `setimmutable/clone`. The TypeScript source includes generic typing with path-aware inference up to 31 levels deep (the published npm package doesn't yet ship the `.d.ts` declaration files).

## When to reach for it

- Redux reducers (or any Flux-style store) with deeply nested state.
- Frozen structures where you need real immutability, not just a shallow one.
- Anywhere you're currently hand-writing nested spreads and want to remove the risk of mutating by mistake.

It's a small library with a very specific goal: if your pain point is "too many nested spreads" or "my shallow freeze isn't protecting what I need," it's worth a look.

**Repo:** [github.com/JonDotsoy/setImmutable.js](https://github.com/JonDotsoy/setImmutable.js) · MIT License

## Similar posts on daily.dev

- [Experiment: making TypeScript immutable-by-default](https://daily.dev/posts/experiment-making-typescript-immutable-by-default-wsz7yxyng) · Hacker News · 0 upvotes · 0 comments
- [arximboldi/immer: Postmodern immutable and persistent data structures for C\+\+ — value semantics at scale](https://daily.dev/posts/arximboldi-immer-postmodern-immutable-and-persistent-data-structures-for-c-value-semantics-at-s-up8yn9jzo) · Hacker News · 3 upvotes · 0 comments
- [Designing real systems with immutable data in Clojure](https://daily.dev/posts/designing-real-systems-with-immutable-data-in-clojure-wdvqc5itp) · Nubank · 0 upvotes · 0 comments
- [Bring Immutability and Context to Arrays](https://daily.dev/posts/bring-immutability-and-context-to-arrays-mipldambi) · TypeScript.TV · 13 upvotes · 0 comments

---

Tags: [#javascript](https://daily.dev/tags/javascript), [#react](https://daily.dev/tags/react), [#nodejs](https://daily.dev/tags/nodejs), [#redux](https://daily.dev/tags/redux)

[View this post on daily.dev](https://daily.dev/posts/setimmutable-immutable-updates-without-wrestling-the-spread-operator-cxr5qrigc)

```json
{"@context":"https://schema.org","@graph":[{"@type":"Organization","@id":"https://daily.dev/#organization","name":"daily.dev","url":"https://daily.dev","logo":{"@type":"ImageObject","url":"https://daily.dev/apple-touch-icon.png","width":180,"height":180},"sameAs":["https://twitter.com/dailydotdev","https://github.com/dailydotdev","https://www.linkedin.com/company/daily-dev-ltd"]},{"@type":"WebSite","@id":"https://daily.dev/#website","url":"https://daily.dev","name":"daily.dev","publisher":{"@id":"https://daily.dev/#organization"},"potentialAction":{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https://daily.dev/search?q={search_term_string}"},"query-input":"required name=search_term_string"}}]}
{"@context":"https://schema.org","@type":"DiscussionForumPosting","mainEntityOfPage":"https://daily.dev/posts/setimmutable-immutable-updates-without-wrestling-the-spread-operator-cxr5qrigc","headline":"setimmutable: immutable updates without wrestling the spread operator","text":"setimmutable is a small npm library offering an immutable alternative to lodash.set, designed for deeply nested state updates without hand-writing spread operators. It rebuilds only the object tree path being changed while preserving reference equality for untouched branches, which matters for Redux selectors and React.memo. The API includes set(), clone(), and map() for batched updates, plus support for custom cloning of class instances. Unlike Object.freeze, which only freezes the first level of an object, setimmutable's structural-sharing approach protects the whole tree regardless of freezing.","url":"https://daily.dev/posts/setimmutable-immutable-updates-without-wrestling-the-spread-operator-cxr5qrigc","datePublished":"2026-09-07T05:17:35.473Z","dateModified":"2026-09-07T05:17:56.855Z","author":{"@type":"Person","name":"Jonathan Delgado","url":"https://daily.dev/jonathandelgado","image":"https://avatars.githubusercontent.com/u/3086539?v=4","description":"A software enginner","worksFor":{"@type":"Organization","name":"Apply Digital","logo":"https://res.cloudinary.com/daily-now/image/upload/s--dPm9XRjU--/f_auto/v1728569477/companies/applydigital"},"interactionStatistic":{"@type":"InteractionCounter","interactionType":{"@type":"EndorseAction"},"userInteractionCount":60}},"image":"https://media.daily.dev/image/upload/s--7sLwvKe7--/f_auto/v1788758256/posts/CXR5qrIgC?_a=BAMAMicg0","interactionStatistic":[{"@type":"InteractionCounter","interactionType":{"@type":"LikeAction"},"userInteractionCount":0},{"@type":"InteractionCounter","interactionType":{"@type":"CommentAction"},"userInteractionCount":0}],"isPartOf":{"@type":"WebPage","url":"https://daily.dev/sources/ccmfsskv5iewk1pmun3oj","name":"Jonathan Delgado"}}
{"@context":"https://schema.org","@type":"BreadcrumbList","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https://daily.dev"},{"@type":"ListItem","position":2,"name":"Jonathan Delgado","item":"https://daily.dev/sources/ccmfsskv5iewk1pmun3oj"},{"@type":"ListItem","position":3,"name":"setimmutable: immutable updates without wrestling the spread operator"}]}
```

