Spread Operator — Handle with Care

Mohit Popli
3 min readFeb 21, 2021

In this article, I’m going to talk about spread operator in Javascript/Typescript along with it’s usage in React.

Well many of us is aware of this tiny little ... operator that serves a wonderful purpose in life of software developers working with client side technologies and React is one of them that also let us use this feature while creating components for our web app.

Spread Operator

For those who still don’t know what it does, let’s just understand what it is and why it fancy developers to use it more frequently

As per MDN, Spread syntax (...) allows an iterable such as an array expression or string to be expanded in places where zero or more arguments (for function calls) or elements (for array literals) are expected, or an object expression to be expanded in places where zero or more key-value pairs (for object literals) are expected.

Let’s just see what the heck above definition wants to convey. I remember a small interview question asked to me long time back, like “Given an array of numbers, find maximum number in the array using max function from Math library

So in the above example we can clearly I have used spread operator to expand the elements of the array so that Math.max() can do it’s job as it only works on parameters containing numbers.

Well now we know what spread operator is. It’s time to see it in action in React, as this article is all about discussing this operator’s good and bad sides.

I am going to create 2 very simple React components. Child component will be strictly typed with props that it’s going to take and Parent component that will render Child component and provide the props required by Child component

Very simple to understand as we spread the props in Child component and used it easily. Cool!!

Now let’s do something nasty and try to see when spread operator will act as a evil for us, how about if I do something like this 👇

And voila!! With the help of spread operator we are successful to pass unnecessary props to Child component that it never expected. Even TS compiler never informed or complained regarding this.

Now to prevent this another way one can think of is strictly providing type for props object to inform TS compiler about it’s contents.

Spread attributes can be useful but they also make it easy to pass unnecessary props to components that don’t care about them or to pass invalid HTML attributes to the DOM. We recommend using this syntax sparingly.

Above statement is from React docs, where they also mentioned to use it at our own risk.

I would like to say ... operator is our friend in need but it can bring some stress along with it. So handle this with care 🤞

Hope it help you guys to avoid such pitfalls!! Happy coding ✌️

If you like the article, don’t forget to clap 😇

--

--

Mohit Popli

Software Engineer @Malaysia | Innovator | @twitter m_popli5 | @insta m.popli5