Blog>
Snippets

Immutable State Update Patterns

Provide code examples for immutable update patterns with array/object spread syntax to avoid accidental state mutations that can lead to type inconsistencies.
// HTML
<div id="app"></div>
An HTML div element with the id 'app' that serves as the mount point for the JavaScript content.
/* CSS */
#app {
    font-family: Arial, sans-serif;
}
CSS to style the #app div with Arial font.
// JS: Updating an object immutably with object spread syntax
const originalState = { a: 1, b: 2 };
const newState = { ...originalState, b: 3 };
// originalState still has b: 2, but newState has b: 3
JavaScript showing how to use object spread syntax to create a new state object with updated properties, while keeping the original state immutable.
// JS: Updating an array immutably with array spread syntax
const originalArray = [1, 2, 3];
const newArray = [...originalArray, 4]; // originalArray still [1, 2, 3], newArray is [1, 2, 3, 4]
JavaScript demonstrating how to use array spread syntax to add a new item to an array, resulting in a new array, without mutating the original.
// JS: Updating an array immutably by replacing an item
const array = [1, 2, 3];
const indexToUpdate = 1;
const newItem = 4;
const updatedArray = [...array.slice(0, indexToUpdate), newItem, ...array.slice(indexToUpdate + 1)];
JavaScript for updating an array by replacing an item at a specific index, without mutating the original array.
// JS: Deleting an item from an array immutably
const array = [1, 2, 3];
const indexToDelete = 1;
const newArray = [...array.slice(0, indexToDelete), ...array.slice(indexToDelete + 1)];
JavaScript showing how to delete an item from an array based on its index, by creating a new array that excludes that item, thus staying immutable.
// JS: Adding an element to an object immutably
const object = { key1: 'value1' };
const newKey = 'key2';
const newValue = 'value2';
const newObject = { ...object, [newKey]: newValue };
JavaScript illustrating how to add a new key-value pair to an object immutably, using the spread syntax and computed property names.
// JS: Removing a key from an object immutably
const object = { key1: 'value1', key2: 'value2' };
const keyToRemove = 'key2';
const { [keyToRemove]: removed, ...newObject } = object;
JavaScript snippet that demonstrates how to remove a key from an object immutably by using object destructuring to omit the key in question while creating a new object.