How to use the spread operator (...) in React
Tags: react, javascript, spreadsyntax, beginners
Published: 2023-03-01 01:47:49

## Introduction

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. The spread syntax might seem odd at first, but if you have the fundamentals of JavaScript down, it might be easier to learn than you think.

In this post, I’ll teach you all about it and show you how to use spread with React. This is what we will cover:

📍 What is the spread operator?
📍 The spread operator syntax

If you already know what the spread operator is, you can jump here: 

📍 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. 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.


![Example use of the spread syntax](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ntj8cg7nipbrfgf5bf4p.png)

## 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. 

### Creating shallow copies of arrays

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.

```javascript
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); 

/* 
["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!

### Concatenating arrays

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

```javascript
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"]
*/
```

### Adding elements to an object

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!

```javascript
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"
		}
  }
*/
```


### Spreading an  array to function arguments

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

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

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

In this example, the function `Math.min()` returns the lowest number within the `expPrice` array. We are spreading the expPrice array into its arguments, as the  `Math.min()` function takes a series of values and not an array. 

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](https://scrimba.com/articles/react-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 Airnb 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`

```jsx
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 ⏰

```jsx
//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! ⚡

```jsx
//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. 


![Render of example code](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lz77rkk6qtslzwr14ixo.png)

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4hmmwljffrzjaqzeytos.png)



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](https://scrimba.com/articles/react-list-array-with-map-function/), 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! See you next time 💯