Product
Introducing Ruby Support in Socket
Socket is launching Ruby support for all users. Enhance your Rails projects with AI-powered security scans for vulnerabilities and supply chain threats. Now in Beta!
Immer is a package that allows you to work with immutable state in a more convenient way. It uses a copy-on-write mechanism to ensure that the original state is not mutated. Instead, Immer produces a new updated state based on the changes made within a 'produce' function. This approach simplifies the process of updating immutable data structures, especially in the context of modern JavaScript frameworks and libraries such as React and Redux.
Creating the next immutable state by modifying the current state
This feature allows you to pass a base state and a producer function to the 'produce' function. Within the producer function, you can mutate the draft state as if it were mutable. Immer takes care of applying the changes to produce the next immutable state.
import produce from 'immer';
const baseState = [
{todo: 'Learn typescript', done: true},
{todo: 'Try immer', done: false}
];
const nextState = produce(baseState, draftState => {
draftState.push({todo: 'Tweet about it'});
draftState[1].done = true;
});
Working with nested structures
Immer can handle deeply nested structures with ease. You can update deeply nested properties without the need to manually copy every level of the structure.
import produce from 'immer';
const baseState = {
user: {
name: 'Michele',
age: 33,
todos: [
{title: 'Tweet about it', done: false}
]
}
};
const nextState = produce(baseState, draftState => {
draftState.user.age = 34;
draftState.user.todos[0].done = true;
});
Currying
Immer supports currying, which means you can predefine a producer function and then apply it to different states. This is useful for creating reusable state transformers.
import produce from 'immer';
const baseState = {counter: 0};
const increment = produce(draft => {
draft.counter++;
});
const nextState = increment(baseState);
Immutable.js is a library by Facebook that provides persistent immutable data structures. Unlike Immer, which allows you to write mutable code that gets converted to immutable updates, Immutable.js requires you to use specific methods to update data structures. It offers a wide range of data structures like List, Map, Set, etc.
Mori is a library that brings Clojure's persistent data structures to JavaScript. It is similar to Immutable.js in that it provides a variety of immutable data structures and functional programming utilities. Mori's API is quite different from JavaScript's native arrays and objects, which can have a steeper learning curve compared to Immer.
Seamless-immutable is a library that provides immutability for your data structures without drastically changing the syntax of standard JavaScript objects and arrays. It is less powerful than Immer in terms of handling complex updates and nested structures but offers a simpler and more familiar API for those who prefer to work with plain JavaScript objects.
Immer (German for: always) is a tiny package that allows you work with immutable state in a more convenient way. It is based on copy-on-write mechanism.
The basic idea is that you will modify (a proxy of) the current state, and once that is completed, the copy will be finalized and form the next state. As soon as a piece of the state is modified, it is copied. That is what one typically does by hand (in for example Redux reducers).
This means that you can interact with your data by using mutations, will keeping all the benefits of immutable data
The immer package exposes a single function:
immer(currentState, fn: (state) => void): nextState
const baseState = [
{
todo: "Learn typescript",
done: true
},
{
todo: "Try immer",
done: false
}
]
const nextState = immer(baseState, state => {
state.push({ todo: "Tweet about it" })
state[1].done = true
})
The interesting thing about immer
is that baseState
will be untouched, but that nextState
will reflect all changes made to state
.
// the new item is only added to the next state,
// base state is unmodified
expect(baseState.length).toBe(2)
expect(nextState.length).toBe(3)
// same for the changed 'done' prop
expect(baseState[1].done).toBe(false)
expect(nextState[1].done).toBe(true)
// unchanged data is structurally shared
expect(nextState[0]).toBe(baseState[0])
// changed data not (dûh)
expect(nextState[1]).not.toBe(baseState[1])
A lot of words; here is a simple example of what difference that could make in practice. The todo reducers from the official Redux todos-with-undo example
const todo = (state, action) => {
switch (action.type) {
case 'ADD_TODO':
return {
id: action.id,
text: action.text,
completed: false
}
case 'TOGGLE_TODO':
if (state.id !== action.id) {
return state
}
return {
...state,
completed: !state.completed
}
default:
return state
}
}
const todos = (state = [], action) => {
switch (action.type) {
case 'ADD_TODO':
return [
...state,
todo(undefined, action)
]
case 'TOGGLE_TODO':
return state.map(t =>
todo(t, action)
)
default:
return state
}
}
After using immer, that simply becomes:
import immer from 'immer'
const todos = (state = [], action) =>
immer(state, state => {
switch (action.type) {
case 'ADD_TODO':
state.push({
id: action.id,
text: action.text,
completed: false
})
return
case 'TOGGLE_TODO':
const todo = state.find(todo => todo.id === action.id)
todo.completed = !todo.completed
return
}
})
Creating middleware or reducer wrapper that applies immer
automatically is left as exercise to the reader :-).
Map
, Set
) not (yet). (PR's welcome)immer
!FAQs
Create your next immutable state by mutating the current one
The npm package immer receives a total of 9,155,251 weekly downloads. As such, immer popularity was classified as popular.
We found that immer demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 2 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Product
Socket is launching Ruby support for all users. Enhance your Rails projects with AI-powered security scans for vulnerabilities and supply chain threats. Now in Beta!
Product
Ensure open-source compliance with Socket’s License Enforcement Beta. Set up your License Policy and secure your software!
Product
We're launching a new set of license analysis and compliance features for analyzing, managing, and complying with licenses across a range of supported languages and ecosystems.