A Cautionary tale about the spread operator

I have been using the ES6 syntax for making copies of objects when React/Redux demanded we return a new copy every time we made a change to the state.

This syntax is

This works great because the spread operator creates a copy of all the keys in the original object. Except… Something that is easy to forget is that it is a shallow copy.

This means that if we have a nested object, the 1st level will be copied by value but every level that’s further nested will be copied by reference! Who would have thunk?

Take a look at this example

We would assume that we get a new object to play with as we deem fit. But if we change a value that’s 2 levels deep as above, we end up mutating the original object and React/Redux will not work as expected because they depend on brand new objects that they can compare with the old objects.

Instead we could do something like

Notice we are using the spread operator at every level of nesting.

In summary, remember that the spread operator gives you a shallow copy.
Also, keep your redux state as flat as possible so you don’t have to deal with such situations.
Happy coding!

The magic of Parcel

Yo frontend web-dev world, I know it’s early for Thanksgiving, but I’m grateful for Parceljs (parceljs.org). It’s an amazing tool because of the zero-configuration approach it promises for web-dev projects.

Disclaimer – I have no affiliation with Parcel, just a dev crush.

I started learning about bundlers and task runners back when Grunt was more popular.

I slowly evolved my understanding of the fragmented and complicated world of web development and understood that to use the latest technologies and specifications wasn’t as easy as updating to the latest version of Java which came with it’s own compiler.

I soon learnt about polyfills and how Babel was the champion of the polyfill world. A polyfill, in short, is something that adds code that a browser might not know.

Long story short, I had to first learn about how to setup Babel with Webpack, and then learn about file loaders, and code splitting and build paths and entry points and so on. All necessary to use modern ES6 syntax.

I did learn it. But I didn’t like it when I wanted to quickly setup a new project that uses all these modern features.

Enter Parcel! It’s so simple that it includes all of these things pre-configured for you.

All anyone needs now is an index.html file that has a script src entry to a javascript file (say index.js). This index.js file then could include other modules and so on. Parcel understands all. Honestly that should be their tagline.

I can’t speak for large apps and production builds where you might want a specific configuration that’s not easy to achieve with Parcel. But I know that it’s going to be my go-to when I think “Oh, wouldn’t it be cool if I can make…”.