React · Junior · Question 15 of 75

What's the right way to add an item to an array in state?

Explanation

State must be updated immutably - by creating a new array. push mutates the existing array, and the reference doesn't change. Non-mutating methods: spread, concat, filter, map, slice, toSorted(). Removal: items.filter(i => i.id !== id).

Further reading

Problem with a question

React · Junior · question 15

Test yourself

Take the React · Junior quiz: questions and options are shuffled, and you get a review of your mistakes at the end.

Take this quiz