Using the spread operator in React setState

I’m currently building an app using React.js and ran into an issue that had me stumped. When a button in the app is clicked, I needed a piece of the state to be updated. Sounds easy enough. The trick here though is that this particular piece of state is an array of objects. What I needed when the button was clicked was to have a new object added to this array.

I got close to a solution but the existing information in the array would just get replaced with the new information. How do I preserve the information in the array while adding to it? I tried using the .push() method in the function I was passing down through the app, but it seemed clunky. There has to be a better way!

That’s when I remembered the spread operator […]. The spread operator can be used to take an existing array and add another element to it while still preserving the original array (famous original array’s?).

var colors = ['red', 'green', 'blue'];
var refColors = [...colors, 'yellow'];
//colors => ['red', 'green', 'blue']
//refColors => ['red', 'green', 'blue', 'yellow']

The app I building is the ever-ubiquitous to do app. It has a few pieces of state, some of which are arrays to hold new notes, old notes, etc. When clicking on a button to add a new note, I wanted that particular array to be updated with the new entry while still preserving the notes it already contained.

This is also what I needed to do for my setState() function. Here is the function that ended up working.

addNote(newNote) {
this.setState({ toDoNotes: [...this.state.toDoNotes, newNote]})

When the .addNote() function is called and passed a newNote object, the toDoNotes section of the state is updated so that it now includes the previous state as well as the addition of newNote.

The spread operator is one of those tools that I tend to forget about because I don’t use it often enough. But when working with updating arrays, combining arrays, or converting node lists into arrays, it is an easy way to get the job done.

Thanks for reading!

Like what you read? Give Jason Arnold a round of applause.

From a quick cheer to a standing ovation, clap to show how much you enjoyed this story.