Complex Objects in State
With bigger applications, state will likely be more than just primitive values. It is more common to store arrays or objects as state. Arrays and objects in JavaScript, however, are mutable but for React to work properly they should be treated as if they were immutable. In plain terms, we should always replace the array or object in state with a new copy.
Using an Array as the State Value
Adding to the Array
Instead of using .push
which will mutate the array, we use .concat
or the ...
spread operator to create a new array with the new number added at the end.
Removing from an Array
Use the .filter
or .slice
methods. Avoid .pop
, .shift
, and .splice
unless you clone the array first.
Using an Object as the State Value
Object Spread
Remember that we need to create a new copy of the state to trigger React's re-rendering. We can use the same ...
spread operator we used on arrays to make a copy of an object. CAVEAT: For nested objects and arrays, ...
only creates a shallow copy.
Last updated
Was this helpful?