Stumbled upon three dots or an ellipsis in JavaScript and wondered what on earth it means??

Allow me to formally introduce you to the spread operator (...)! ย 

A handy JavaScript feature that makes your code simpler, compact, and more pleasant to write.

Spread might seem odd at first ๐Ÿ‘€ but if you have the fundamentals of JavaScript down, it might be easier to learn than you think.

This post will start with the fundamentals of spread:

  • ๐Ÿ“ What is the spread operator?
  • ๐Ÿ“ The spread operator syntax

If you already know spread and wondering how to use spread with React jump ahead:

  • ๐Ÿ“ How to use the spread operator to spread props in a React component
  • ๐Ÿ“ How to use the spread operator to update state in React
  • ๐Ÿ“ Pros and cons of using the spread syntax to spread props

What is the spread operator?

Introduced with ES6 (the revision of JavaScript valid from 2015), the spread operator allows you to expand - or spread - arrays and objects into multiple elements.

Using the spread operator to combine two arrays into one

This can be useful when copying arrays or objects, or when working with a number of arguments or properties.

In the context of React, the spread operator can be used to spread an object of props onto an element in a React component, making it easier to pass down props to child components but more on that later!

Examples of the Spread Operator

The spread operator is denoted by three dots: ....

Letโ€™s have a look at some use cases for the spread syntax.

Copy an array with spread

If we want to create a shallow copy of an array, we can easily do that using the spread operator.

A shallow copy of an array allows you to work with the data in the copy without affecting the original array.

const airbnbExperiences = [
	"Walk in the woods",
	"Local cooking class", 
	"Guided tour"
];

// creating a shallow copy of the array using
// the spread syntax

const airbnbExperiences = [...airbnbExperiences];

console.log(airbnbExperiences); 

/* result ["Walk in the woods", "Local cooking class",
"Guided tour of the city"] */

Copying an array isnโ€™t something you need to do every day, but letโ€™s build on this syntax with the next example!

Join arrays with spread

Another situation where the spread operator comes in handy is when we need to concatenate two arrays or more arrays.

const airbnbExperiences = [
  "Walk in the woods",
  "Local cooking class",
  "Guided tour of the city",
  ];

const moreAirbnbExperiences = [
  "Night diving",
  "Volcano hike",
  "Language class",
  ];

// concatenating the two arrays into a new one:

const allAirbnbExperiences = 
  [...airbnbExperiences, 
   ...moreAirbnbExperiences];

console.log(allAirbnbExperiences);

/*
["Walk in the woods", 
 "Local cooking class", 
 "Guided tour of the city", 
 "Night diving", 
 "Volcano hike", 
 "Language class"]
*/

Combine objects with spread

Similarly, we can spread the elements of an object and even add new elements using the spread syntax. This is a very powerful feature of the spread syntax and you will likely use it again and again in your daily Javascript chores!

const airbnbListings = {
  exp1: {
    host: "Mario",
    exp: "Walk in the woods",
    location: "Norway",
  },
  exp2: {
    host: "Gloria",
    exp: "Local Cooking Class",
    location: "Italy",
  }
};

const updatedAirbnbListings = {
  ...airbnbExperiences,
  exp3: {
    host: "Tom",
    exp: "Night diving",
    location: "Mexico",
  },
};

console.log(updatedAirbnbListings);

/* 
	{
   exp1: {
    host: "Mario",
    exp: "Walk in the woods",
    location: "Norway",
	  },
   exp2: {
    host: "Gloria",
    exp: "Local Cooking Class",
    location: "Italy",
	  },
   exp3: {
		host: "Tom", 
		exp: "Night diving", 
		location: "Mexico"
		}
  }
*/

Spread an array to function arguments

Math.min is an odd duckling. You might expect to pass it an array of values but it actually expects an infinite number of Number arguments.

Math.min([29, 39, 9, 114]) // โŒ
Math.min(29, 39, 9, 114) // โœ…

What would you do if you had an array but needed to find the minimum value?

Spread to the rescue!

We can also use the spread syntax to spread the elements of an array as separate arguments when calling a function:

const expPrice = [29, 39, 9, 114] 

console.log (Math.min(...expPrice)) // 9  

If you got the gist of how we can use the spread operator, letโ€™s move to some practical use cases in React!

How to use the spread operator to spread props in a React component

The spread syntax can be very useful in React components, especially when dealing with props. ย To thoroughly understand this section, you need to be familiar with React components, their parent-child relationships, and props. If you struggle to understand props or you simply want to refresh your knowledge, we wrote this thorough tutorial on props!

Props is an object, and as we have just seen, an object can be spread into its multiple key-value pairs using the spread operator.

Letโ€™s build a small app to display data about Airbnb Experiences.

We start by building a component called AirbnbListing, which receives props. In this case, props is an object containing information about the user:

  • host
  • experience
  • location
  • price
export default function AirbnbListing(props) {
  return (
    <div>
      <p>Host: {props.host}</p>
      <p>Experience: {props.experience}</p>
      <p>Location: {props.location}</p>
      <p>Price: {props.price}</p>
    </div>
  );
}

In our App, we can render the AirbnbListing component. Now, how do we pass the props to the component? We have two chances:

1. Declaring the props one by one โฐ

//Scenario 1: declare every prop

import AirbnbListing from "./components/AirbnbListing";

const props = {
  host: "Mario",
  experience: "Walk in the woods",
  location: "Norway",
  price: 29,
};

export default function App() {
  return (
    <div>
      <AirbnbListing
        host={props.host}
        experience={props.experience}
        location={props.location}
        price={props.price}
      />
    </div>
  );
}

2. Using the spread syntax to pass the whole props object in one easy go! โšก

//Scenario 2: using the spread operator

import AirbnbListing from "./components/AirbnbListing";

const props = {
  host: "Mario",
  experience: "Walk in the woods",
  location: "Norway",
  price: 29,
};

export default function App() {
  return (
    <div>
      <AirbnbListing {...props} />
    </div>
  );
}

What we render is exactly the same.

Rendering the component

If you have followed so far, congratulations! ๐ŸŽ‰ Spreading props in React is not an easy concept and you may have wondered: if what we render is the same, should I actually use the spread operator? This is what we are tackling next.

Pros and cons of using the spread syntax to spread props

There are some pros and cons to using the spread syntax in React components.

On one hand, it can save a lot of time and typing when you have a large number of props that you need to pass to a component, making the code less verbose.

On the other hand, spreading props obscures the properties we are passing to a component: to see them, we would need to shift to the file where props are declared, therefore making it difficult to see at a glance what props are being passed to a component.

Note: in our code example, the props are declared in the same file for clarity, but this is not usually the case.
Pros and cons of using the spread syntax to spread props

Ultimately, it is a matter of how you feel more comfortable. It is best to stick with the accepted standard of the company or the React project you are working for.

The Verdict

In this article we have seen how useful the spread operator can be when working with props in React. When used together with other methods, such as the .map method, it can save precious time and make the code more concise. Still, it's always important to strike a balance between conciseness and readability! Use it at your own discretion and critically evaluate the specific situation.

I hope you enjoyed the article and you learned a thing or two about the spread operator. See you next time! ๐Ÿ’ฏ