The SpreadOperator is a JS ES6 feature that allows developers to expand array (and objects) into individual element or properties. It’s commonly used in React to copy arrays or objects, merge them, or update states and pass props to components.

Uses

Copying and/or combining arrays and objects

Arrays:

const array1 = [1, 2, 3];
const array2 = [4, 5, 6];
const combined = [...array1, ...array2]; // [1, 2, 3, 4, 5, 6]

Combines the arrays without mutating the original arrays. Objects:

const obj1 = { a: 1, b: 2 };
const obj2 = { b: 3, c: 4 };
const merged = { ...obj1, ...obj2 }; // { a: 1, b: 3, c: 4 }

Here, the elements (properties) from obj2 will overwrite those from obj1 if they share identical keys…

Passing props to Components

The SpreadOperator allows passing all properties of an object as props

const props = {type: 'button', className='btn',disabled: false};
<MyButton {...props} />

Updating State in React

When updating state that uses arrays or objects, the spread operator helps maintain immutability by creating a copy and using it to update the state.

// Arrays
setItems([...items, newItems]); // this updates (copies) items with newItems
 
// Objects
setUser({...user, name: 'Alice'});

This ensure that the original objects are not mutated.

Spread vs. Rest syntax

  • Spread (...array) or (...obj) expands an array or object into elements/properties.
  • Rest (...[...]) in ArrayDestructuring e.g. const [first, ...rest] = array collects the remaining elements into a new array. Example of rest syntax:
const numbers = [1, 2, 3, 4];
const [first, ...rest] = numbers; // first = 1, rest = [2, 3, 4]

// Spread and Rest have similar syntax but Opposite purposes.

Practical Examples in React

Use CaseExample CodeResult
Copy arrayconst copy = [...array];Shallow copy of array
Merge arraysconst merged = [...arr1, ...arr2];Combined array
Copy/merge objectsconst newObj = {...obj1, ...obj2};Combined object
Pass props to component<Component {...props} />All props passed as component props
Update array in statesetState([...state, newItem]);New array with newItem added
Update object in statesetState({ ...state, key: value });New object with updated/added key