Explain Codes LogoExplain Codes Logo

What are these three dots in React doing?

javascript
spread-operator
react
typescript
Nikita BarsukovbyNikita Barsukov·Mar 10, 2025
TLDR

The ... in React is the spread operator, a nifty syntax that allows you to unpack iterables into intrinsic elements. It comes in handy to seamlessly merge arrays or amalgamate object attributes:

Array example:

const alphabetArray = ['a', 'b']; // Spread operator forming an "alphabet trio" const updatedArray = [...alphabetArray, 'c']; // ['a', 'b', 'c']

Object example:

const basicConfig = { theme: 'light' }; // Spread operator spicing things up in the config const updatedConfig = { ...basicConfig, overrideTheme: 'dark' }; // { theme: 'light', overrideTheme: 'dark' }

In the realm of React, it redefines the process of conveying props to components:

// John Doe sending his regards through props! const userProps = { firstName: 'John', lastName: 'Doe' }; <Component {...userProps} /> // Voila! firstName and lastName props welcomed in the Component

Deep-diving props propagation

The integral power of the spread operator manifests itself in the realm of React. Explore its practical applications:

  • Immutable State Surprise: A neat trick to keep the good old parts of the state unaltered while freshening up:

    // State cheering, "Same old, same old. Oh wait! Something's new." this.setState(prev => ({ ...prev, updated: true }));
  • Config Merge Magic: Pool together different configurations while strategically overriding selective keys:

    // When defaultConfig met userConfig. What a twist in the plot const defaultConfig = { color: 'blue', size: 'medium' }; const userConfig = { color: 'red' }; const finalConfig = { ...defaultConfig, ...userConfig }; // { color: 'red', size: 'medium' }
  • Essence Extraction and Remaining Reunion: Extract specific properties from an object and letting the rest stay buddies!

    // Surprisingly, not all Johns are identical const { firstName, ...remainingProps } = user;
  • Parent to Child Heritage: Inheriting traits, or parent props the easy way and passing them down to child components:

    // Here momma, passin' props like momma <ParentComponent> <ChildComponent {...props} /> </ParentComponent>

Function play with spreads

The spread operator is a drama queen when used within functions:

  • Gathering Factors: Transforms a sea of arguments into a peaceful array island:

    // Just a normal function, stashing all arguments in a safe function stashArguments(...args) { console.log(args); }
  • Spilling Arguments for Calling: Summon a function, spreading an array into individual arguments:

    // args lived happily ever after as individual arguments const args = [1, 2, 3]; someFunction(...args);
  • Math Masterstroke: Apply Math methods onto arrays as if they were independent arguments:

    // Discovering math genius amongst numbers! const numbers = [1, 2, 3]; const maxNumber = Math.max(...numbers);

Array Artifact

The aptitude of the spread syntax gets unleashed with arrays in various operations:

  • Copy-Paste and Merge: Brew a new array that borrows or blends elements from existing ones:

    // When array1 met array2, it was a strong reflection const array1 = [1, 2, 3]; const array2 = [...array1, 4, 5]; // [1, 2, 3, 4, 5]
  • Unleash and Mix: Unpack elements from an array to be part of a new squad or function arguments:

    // newArray, "Best of both worlds!" const newArray = [...array1, ...array2];
  • String Disintegration: Fragment a string into an array of alphabets:

    // "Hello to you too, letters!" const greatings = 'hello'; const letters = [...greatings]; // ['h', 'e', 'l', 'l', 'o']

TypeScript telltales

The spread operator and TypeScript: are they friends or foes? TypeScript wholeheartedly embraces and transpiles the spread syntax. But don't let your guard down, watch out for certain traps, such as:

  • TypeName compatibility when dealing types
  • Tuple and enum spreading in typed scenarios
  • Rest elements in tuple types

Quirk Quotient

A word of caution while working with the spread operator, each power comes with its potential caveats:

  • Performance Plateau: Excessive use of spread could lead to performance penalty, especially in large-scale applications. Keep your spreads in check!
  • Dancing on the Edge: The spread operator performs a shallow copy, and if altered, nested objects may give rise to cloning calamities (mutation bugs).
  • TypeScript Typing Torment: Keep your TypeScript typings clean and clear to ward off transpilation troubles.