Sign in
Log inSign up
Wait, How Does the Spread Operator in React Work Again?

Wait, How Does the Spread Operator in React Work Again?

You've read the MDN docs. Spread operator, got it. But, when you see those dots with props, you freeze, asking yourself, how does this work again?

JavaScriptErika's photo
JavaScriptErika
·Mar 16, 2022·

5 min read

The three little dots you'll see with props in React, in this context, is known as the spread operator. It's a tiny shortcut to make life easier. 👁️👄👁️

We're going to take a look at what's really going on.

Let's say we have a root beer object 🥤:

const rootBeerData = {
  dietOrRegular: "regular",
  size: "large",
  iceCream: true,
  price: "3.50"
}

And let's say I have this cool component (a freaking Root Beer Machine!!). I want to make a root beer float, and to do that, I need to pass in the rootBeerData object to our machine. We could do it this way, without the three dots:

<RootBeerMachine 
  dietOrRegular={rootBeerData.dietOrRegular} 
  size={rootBeerData.size} 
  iceCream={rootBeerData.iceCream} 
  price={rootBeerData.price} 
/>

We are passing our <RootbeerMachine /> component: dietOrRegular, size, iceCream, and price which are custom name attributes (we could have named them anything), and I'm assigning each of them the keys from rootBeerData to grab the values.

There's nothing wrong with it, it's valid and it works. Just like flat soda --it wets the whistle with a hint of disappointment 😏 (I kid! there's a time and place for everything).

If we give our <RootBeerMachine /> those three little dots, it saves you from typing all of that mess out.

<RootBeerMachine {...rootBeerData } />

We're essentially copying our rootBeerData object into the props object! Under the hood, props looks like this:

  props : {
    dietOrRegular: "regular",
    size: "large",
    iceCream: true,
    price: "3.50"
}

Looking at the props object we have above, we can take note of two things:

  • Our keys from the rootBeerData are now the custom attributes that hold the values from rootBeerData.

  • The three little dots copies our key value pairs from the rootBeerData object and pastes them in our props. Those triple dots are a prop-makin' machine! 😉🥤🦾

What if our <RootbeerMachine /> accepted rootBeerData as ...props instead?


const rootBeerData = {
  dietOrRegular: "regular",
  size: "large",
  iceCream: true,
  price: "3.50"
}

We have a functional component here called <RootBeerBase />. We're passing our rootBeerData object into our <RootBeerIngredients /> component.

const RootBeerBase = () => {
  return (
   <RootBeerIngredients {...rootBeerData} />
   /* Conceptually, this is similar to looking like:
    <RootBeerIngredients 
      dietOrRegular="regular"
      size="large"
      iceCream={true} 
      price="3.50"
    />
*/
  )
}

<RootBeerIngredients /> is now accepting and passing our props (that has a copy of the key/value pairs from rootBeerData) to <RootBeerMachine />

const RootBeerIngredients = props => { 
  return (
   <RootBeerMachine {...props} />
  )
}

The props object getting passed into our RootBeerMachine contains the rootBeerData, and is getting copied into 's prop object. We're just copying and pasting over here.

  props : {
    dietOrRegular: "regular",
    size: "large",
    iceCream: true,
    price: "3.50"
  }

Now we want to use our props after passing them down 🥵. Anyone else thirsty?

We could destructure our parameters from props. That way, we wont' need to constantly write out props.dietOrRegular, props.size, props.iceCream, or props.price 🥴.

Destructuring is super common in React with the spread operator, so let's just touch on it here. Should I write an article on how that's used with React? Let me know in the comments!

The beauty of destructuring your props is, the key(s) from the object you extract from, turn into your variable name with the value assignment. It's a 2 in 1 package deal, just like a root beer float. Ya'll, this RootBeerMachine's mechanics are truly magical. 🦄✨

//destructuring our props 
const RootBeerMachine = ({dietOrRegular, size, iceCream, price}) => {
 return (
  <div>
     /* we can easily access our props!*/
     {dietOrRegular}
     {size}
     {iceCream}
     {price}
  </div>
 )
}

You can and may also come across destructuring props this way too! 🍦🍦🍦 Both are valid and a style preference 💅

const RootBeerMachine = props => {
  const {dietOrRegular, size, iceCream, price } = props
   return (
    <div>
       /* we can easily access our props!*/
       {dietOrRegular}
       {size}
       {iceCream}
    </div>
 )
}

The three dots aka spread operator are helpful because what if you have a ton of key/value pairs you want to pass in? You no longer have to write out props manually or come up with creative prop names in a sea of components! 🎉

On the other side, you are giving <RootBeerMachine /> every single prop from rootBeerData even if you don't use them all.

What if <RootBeerMachine /> doesn't care about price, it cares about ingredients only? Even if price is passed to it and we weren't gonna use it, thankfully <RootBeerMachine /> will only use what it needs to make us the perfect float.

While the spread operator pattern is an awesome shortcut to use, use those three little dots with these things in mind:

  • Do I pass in props that are mostly, if not all, being used?
  • Does it make my code more readable?

Just like you wouldn't drink a root beer float all of the time 🙈😨, use caution and back up why you're using the spread operator. Be nice to your coworkers and future self, write a comment or use TypeScript to figure out what that destructured object looks like. Leave surprises for parties 🥳, not your code 🍝.

And in case you were wondering, the root beer float didn't disappoint.😋

Ps. The best way to learn is to experiment! If you do a {console.log({...props}} vs {console.log({props}} inside your component, you'll get to see what's going on -- it looks the same!! Don't take my word for it, it's best to SEE it in action - checkout this CodeSandbox I made just for you. 🎁

Our tech community is awesome. 🌟 I asked on Twitter if anyone would be open to proofreading this article, and the following developers volunteered. Thank you for your technical edits and feedback- they're great people to connect with! 🙏

Andy Van Slaars, Deji Adesoga, Max Walters & Ryan Killeen

Did this article help? 💜 or 👎 root beer floats? Let me know in the comments and let's connect on Twitter! 😄

Hassle-free blogging platform that developers and teams love.
  • Docs by Hashnode
    New
  • Blogs
  • AI Markdown Editor
  • GraphQL APIs
  • Open source Starter-kit

© Hashnode 2024 — LinearBytes Inc.

Privacy PolicyTermsCode of Conduct