Drills Repository
16 Drills · All Belts · immutability
Mutating object state directly
React state must be treated as immutable, since React detects updates by comparing references, not by inspecting values. Mutating the existing object keeps the same reference, so React never registers a change and skips re-rendering.
Losing state fields during object update
State setters returned by useState replace the entire stored value rather than shallow-merging it the way class component setState once did. Since the new object contains only lastName, every other field on the previous state object is lost.
Array mutation with push
push() mutates the existing array instead of creating a new one. React relies on state replacement and reference changes to know that it should re-render.
slice vs splice confusion
slice() creates a copy of part or all of an array without mutating the original. Methods like splice(), pop(), and reverse() mutate the existing array, which can break React's immutable state expectations.
Removing items immutably
filter() returns a new array containing only the items that pass the condition. This preserves immutability and provides React with a new array reference for rendering.
Shallow spread copy limitation
Object spread syntax copies only the top-level properties of an object, leaving nested objects as shared references. Mutating a nested object therefore affects both the original and the spread copy simultaneously.
Updating nested object state correctly
Updating nested state immutably requires creating new copies at every level along the changed path. Spreading both the nested artwork object and its parent object preserves all unrelated fields while replacing only the modified data.
Local mutation vs state mutation
Mutating a freshly created object is safe because no other code references it yet. Problems occur when existing state, props, or shared objects are mutated because React relies on immutable snapshots and reference comparisons.
Updating one item with map
map() allows React developers to create a new array while selectively replacing only the changed item. Combined with object spread syntax, this preserves immutability and keeps unchanged items intact.
Reverse and sort with immutable updates
Methods like reverse() mutate arrays, so React state should first be copied using spread syntax or another non-mutating technique. Mutating the copied array is safe because it is a fresh object not shared with existing state.
Copying arrays does not copy nested objects
Array spread creates a new top-level array, but the objects it contains remain shared references with the original array. Mutating an item at an index therefore also mutates the corresponding object in the original state.
Shared object reference mutation
JavaScript objects are reference-based, so two variables pointing to the same nested object share a single underlying value. Mutating that object through either reference changes what both variables observe.