Updating Arrays in State in React JS
Course: React JS Training
Topic: Updating Arrays in State
Official Documentation: React – Updating Arrays in State
1. Introduction to Updating Arrays in State
In React JS, arrays are commonly used to store collections of related data, such as student records, product lists, shopping cart items, tasks, and user information. Updating arrays in state means adding, removing, replacing, or modifying items in an array and displaying the updated information in the component.
React recommends treating arrays stored in state as read-only. Instead of directly modifying the existing array, create a new array containing the required changes and pass it to the state setter function.
For example, when a user adds a new task to a to-do list, React should display the new task without directly modifying the existing state array.
2. What Is an Array in JavaScript?
An array is a data structure used to store multiple values in a single variable. Array elements are accessed using indexes, starting from zero.
Example:
const fruits = ["Apple", "Banana", "Mango"];
console.log(fruits[0]);
console.log(fruits[1]);
console.log(fruits[2]);
Output:
Apple
Banana
Mango
In this example, the array contains three string values. React components can store arrays in state and update them in response to user interactions.
3. What Is State in React JS?
State is data managed by a React component. When state changes through a state setter, React can render the component again to display the latest data.
The useState() Hook is used to create and manage state in functional components.
Syntax:
const [items, setItems] = useState(initialValue);
- items: The current array stored in state.
- setItems: The function used to request a state update.
- useState(): The React Hook that initializes state.
- initialValue: The initial array or other state value.
Example:
import { useState } from "react";
function FruitList() {
const [fruits, setFruits] = useState([
"Apple",
"Banana",
"Mango"
]);
return (
<div>
<h2>Fruit List</h2>
<ul>
{fruits.map((fruit, index) => (
<li key={index}>{fruit}</li>
))}
</ul>
</div>
);
}
export default FruitList;
Here, the fruits state stores an array of fruit names. The map() method displays each item in the user interface.
4. Why Do We Need to Update Arrays in State?
React applications frequently need to update arrays when users interact with a page. Common examples include:
- Adding new tasks to a to-do list.
- Removing products from a shopping cart.
- Updating student or employee records.
- Adding new comments to a discussion.
- Marking tasks as completed.
- Filtering products by category.
- Updating quantities in a shopping cart.
- Sorting or reversing displayed data.
Correct array updates help keep the user interface consistent with the component's state.
5. Understanding Array Mutation
Mutation means modifying an existing array instead of creating a new array. JavaScript provides several methods that mutate arrays, including push(), pop(), shift(), unshift(), splice(), sort(), and reverse().
Although these methods are valid JavaScript, avoid using them directly on arrays stored in React state.
Incorrect Example:
import { useState } from "react";
function FruitList() {
const [fruits, setFruits] = useState([
"Apple",
"Banana"
]);
function addFruit() {
fruits.push("Mango");
setFruits(fruits);
}
return (
<div>
<ul>
{fruits.map((fruit, index) => (
<li key={index}>{fruit}</li>
))}
</ul>
<button onClick={addFruit}>Add Fruit</button>
</div>
);
}
export default FruitList;
Problem: The push() method modifies the existing array. Passing the same array reference back to setFruits() may cause React to skip the update.
Correct approach: Create a new array containing the existing items and the new item.
6. Adding Items to an Array Using the Spread Operator
The array spread operator (...) copies the elements of an iterable, such as an array, into a new array. It is commonly used to add items to React state without mutating the original array.
Syntax:
setItems([
...items,
newItem
]);
The existing items are copied first, and the new item is added at the end.
Example:
import { useState } from "react";
function FruitList() {
const [fruits, setFruits] = useState([
"Apple",
"Banana"
]);
function addFruit() {
setFruits(previousFruits => [
...previousFruits,
"Mango"
]);
}
return (
<div>
<h2>Fruit List</h2>
<ul>
{fruits.map((fruit, index) => (
<li key={index}>{fruit}</li>
))}
</ul>
<button onClick={addFruit}>Add Fruit</button>
</div>
);
}
export default FruitList;
When the button is clicked, Mango is added to the list. The updater function uses the previous array to produce the next array.
7. Adding Items to the Beginning of an Array
You can add an item to the beginning of an array by placing the new item before the spread expression.
Example:
const [fruits, setFruits] = useState([
"Banana",
"Mango"
]);
function addFruitAtBeginning() {
setFruits(previousFruits => [
"Apple",
...previousFruits
]);
}
Result: Apple appears before Banana and Mango.
8. Removing Items from an Array Using filter()
The filter() method creates a new array containing only the elements that satisfy a specified condition. It is commonly used to remove items from React state.
Syntax:
setItems(previousItems =>
previousItems.filter(item => condition)
);
Example:
import { useState } from "react";
function FruitList() {
const [fruits, setFruits] = useState([
"Apple",
"Banana",
"Mango"
]);
function removeBanana() {
setFruits(previousFruits =>
previousFruits.filter(
fruit => fruit !== "Banana"
)
);
}
return (
<div>
<h2>Fruit List</h2>
<ul>
{fruits.map((fruit, index) => (
<li key={index}>{fruit}</li>
))}
</ul>
<button onClick={removeBanana}>
Remove Banana
</button>
</div>
);
}
export default FruitList;
Explanation: The filter() method keeps every fruit except Banana. React receives the new array and can display the updated list.
9. Updating Items in an Array Using map()
The map() method creates a new array by transforming each element of an existing array. It is useful when you need to replace or update specific items without modifying the original array.
Syntax:
setItems(previousItems =>
previousItems.map(item =>
condition ? updatedItem : item
)
);
Example:
import { useState } from "react";
function NumberList() {
const [numbers, setNumbers] = useState([
10,
20,
30
]);
function updateNumber() {
setNumbers(previousNumbers =>
previousNumbers.map(number =>
number === 20 ? 25 : number
)
);
}
return (
<div>
<h2>Numbers</h2>
<ul>
{numbers.map((number, index) => (
<li key={index}>{number}</li>
))}
</ul>
<button onClick={updateNumber}>
Update Number
</button>
</div>
);
}
export default NumberList;
When the button is clicked, 20 is replaced with 25. The other numbers remain unchanged.
10. Updating Objects Inside an Array
Arrays in React state often contain objects instead of simple values. For example, a task list may contain objects with an ID, title, and completion status. To update a property of one object, use map() to create a new array and the object spread operator to create a new version of the matching object.
Example:
import { useState } from "react";
function TaskList() {
const [tasks, setTasks] = useState([
{ id: 1, title: "Learn HTML", completed: false },
{ id: 2, title: "Learn CSS", completed: false },
{ id: 3, title: "Learn React", completed: false }
]);
function completeTask(taskId) {
setTasks(previousTasks =>
previousTasks.map(task =>
task.id === taskId
? { ...task, completed: true }
: task
)
);
}
return (
<div>
<h2>Task List</h2>
{tasks.map(task => (
<div key={task.id}>
<span>
{task.title} - {task.completed ? "Completed" : "Pending"}
</span>
<button onClick={() => completeTask(task.id)}>
Complete
</button>
</div>
))}
</div>
);
}
export default TaskList;
Explanation: The map() method checks each task's ID. If the ID matches, the component creates a new task object with completed: true. Other tasks remain unchanged.
11. Inserting Items at a Specific Position
Sometimes, you need to insert an item at a particular index instead of adding it to the beginning or end. You can combine the spread operator with slice() to achieve this.
The slice() method returns a portion of an array without modifying the original array.
Example:
const fruits = ["Apple", "Mango", "Orange"];
const insertAt = 1;
const updatedFruits = [
...fruits.slice(0, insertAt),
"Banana",
...fruits.slice(insertAt)
];
console.log(updatedFruits);
Output:
["Apple", "Banana", "Mango", "Orange"]
In this example, Banana is inserted at index 1. The original array remains unchanged.
12. Understanding slice() and splice()
The slice() and splice() methods have similar names but behave differently.
| Feature |
slice() |
splice() |
| Purpose |
Returns a portion of an array. |
Adds, removes, or replaces elements. |
| Mutates original array |
No. |
Yes. |
| Common React use |
Copying portions and inserting items. |
Avoid using directly on state arrays. |
| Return value |
A new array containing selected elements. |
An array of removed elements. |
When working with React state, prefer slice() and other non-mutating techniques over calling splice() directly on an existing state array.
13. Sorting and Reversing Arrays in State
The sort() and reverse() methods modify the array on which they are called. To use them safely with React state, make a copy first.
Example: Reversing an Array
function reverseFruits() {
setFruits(previousFruits => {
const nextFruits = [...previousFruits];
nextFruits.reverse();
return nextFruits;
});
}
Example: Sorting an Array
function sortFruits() {
setFruits(previousFruits =>
[...previousFruits].sort()
);
}
Both examples create a new array before calling a mutating method. This prevents direct mutation of the array stored in state.
14. Updating Array Items Using Their Index
The map() method provides both the current element and its index. You can use the index to update an item at a particular position.
Example:
const [numbers, setNumbers] = useState([
1,
2,
3
]);
function updateSecondNumber() {
setNumbers(previousNumbers =>
previousNumbers.map((number, index) =>
index === 1 ? 100 : number
)
);
}
When the function runs, the second element changes from 2 to 100.
Note: For rendering lists of components, use stable unique IDs as React keys whenever possible instead of array indexes, especially when items can be inserted, removed, or reordered.
15. Using Functional State Updates
A functional state update passes a function to the state setter. React supplies the previous state value to this function, allowing you to calculate the next state from the latest queued value.
Syntax:
setItems(previousItems => {
return [...previousItems, newItem];
});
Example:
function addNumber() {
setNumbers(previousNumbers => [
...previousNumbers,
previousNumbers.length + 1
]);
}
Functional updates are particularly useful when the next array depends on the previous array, such as when adding, removing, or modifying items.
16. Common Array Methods Used in React
| Method |
Purpose |
Mutates Original Array? |
map() |
Transforms elements or replaces selected items. |
No |
filter() |
Removes items by keeping elements that satisfy a condition. |
No |
concat() |
Combines arrays or adds elements to a new array. |
No |
slice() |
Copies a portion of an array. |
No |
push() |
Adds items to the end. |
Yes |
pop() |
Removes the last item. |
Yes |
splice() |
Inserts, removes, or replaces items. |
Yes |
sort() |
Sorts array elements. |
Yes |
reverse() |
Reverses array order. |
Yes |
17. Common Mistakes When Updating Arrays
- Direct mutation: Avoid changing state arrays with
push(), pop(), or direct index assignment.
- Reusing the same array: Passing the original array reference may cause React to skip the update.
- Forgetting existing elements: When adding an item, use the spread operator or
concat() to preserve the existing items.
- Incorrect filtering conditions: Check that your
filter() condition removes the intended elements.
- Mutating objects inside an array: Copy the object that needs to change instead of modifying its properties directly.
- Using unstable keys: Prefer stable unique IDs when rendering dynamic lists.
- Sorting the state array directly: Copy the array before calling
sort() or reverse().
- Ignoring previous state: Use functional updates when the next state depends on the current array.
18. Practical Project: To-Do List Application
Objective: Create a simple React to-do list that allows users to add tasks, mark tasks as completed, and delete tasks.
Complete Code:
import { useState } from "react";
function TodoApp() {
const [taskName, setTaskName] = useState("");
const [tasks, setTasks] = useState([]);
const [nextId, setNextId] = useState(1);
function addTask() {
const trimmedTask = taskName.trim();
if (!trimmedTask) return;
setTasks(previousTasks => [
...previousTasks,
{
id: nextId,
title: trimmedTask,
completed: false
}
]);
setNextId(previousId => previousId + 1);
setTaskName("");
}
function toggleTask(taskId) {
setTasks(previousTasks =>
previousTasks.map(task =>
task.id === taskId
? { ...task, completed: !task.completed }
: task
)
);
}
function deleteTask(taskId) {
setTasks(previousTasks =>
previousTasks.filter(task => task.id !== taskId)
);
}
return (
<div>
<h2>To-Do List</h2>
<input
type="text"
value={taskName}
onChange={event => setTaskName(event.target.value)}
placeholder="Enter a task"
/>
<button onClick={addTask}>Add Task</button>
<ul>
{tasks.map(task => (
<li key={task.id}>
<span>
{task.completed ? "✓ " : ""}
{task.title}
</span>
<button onClick={() => toggleTask(task.id)}>
{task.completed ? "Undo" : "Complete"}
</button>
<button onClick={() => deleteTask(task.id)}>
Delete
</button>
</li>
))}
</ul>
</div>
);
}
export default TodoApp;
Project Explanation:
- The
taskName state stores the text entered by the user.
- The
tasks state stores the task objects in an array.
- The
addTask() function creates a new task and appends it to a new array.
- The
toggleTask() function uses map() to update the selected task.
- The
deleteTask() function uses filter() to remove the selected task.
- The
nextId state provides a unique ID for each task during the component's lifetime.
- The task list is rendered using
map() and stable task IDs.
19. Best Practices for Updating Arrays in State
- Treat arrays stored in React state as read-only.
- Use the spread operator or
concat() to add items.
- Use
filter() to remove items.
- Use
map() to update or replace items.
- Use
slice() to copy portions of arrays.
- Copy an array before using methods such as
sort() or reverse().
- When updating an object inside an array, create a new object for the changed item.
- Use functional state updates when the next state depends on the previous state.
- Use stable unique keys when rendering lists.
- Keep array state simple and avoid unnecessary deeply nested structures.
20. Interview Questions and Answers
Q1. What does updating arrays in state mean in React?
Answer: It means creating a new array with the required changes and passing it to the state setter to update the component's state.
Q2. Why should we avoid mutating arrays in React state?
Answer: Mutating an existing array changes state data without creating a new reference. React may skip the update, and mutation can cause unexpected behavior.
Q3. How can you add an item to an array?
Answer: Use the spread operator, such as setItems(previousItems => [...previousItems, newItem]).
Q4. How can you remove an item from an array?
Answer: Use filter() to create a new array that excludes the item you want to remove.
Q5. How can you update a specific item in an array?
Answer: Use map() to create a new array and return the updated item when its ID or another identifying property matches.
Q6. What is the difference between map() and filter()?
Answer: map() transforms each element and returns an array of corresponding results. filter() returns only the elements that satisfy a condition.
Q7. What is the difference between slice() and splice()?
Answer: slice() returns a portion of an array without modifying the original. splice() modifies the original array by inserting, removing, or replacing elements.
Q8. How do you update an object inside an array?
Answer: Use map() to find the matching object and the object spread operator to create an updated copy of it.
Q9. How do you reverse an array in React state?
Answer: Create a copy using [...items], call reverse() on the copy, and pass the result to the state setter.
Q10. Why are keys important when rendering arrays?
Answer: Keys help React identify list items between renders, particularly when items are added, removed, or reordered. Stable unique IDs are usually preferred.
21. Practice Exercises
- Create a fruit list with a button to add new fruits.
- Create a list of students and remove a student by ID.
- Build a product list where a product's price can be updated.
- Create a to-do list with add, complete, and delete features.
- Insert a new item at a specific position using
slice().
- Create a button that reverses a list without mutating state.
- Sort a list of names by copying the array first.
- Update one property of an object stored inside an array.
22. Quick Revision Checklist
- Understand arrays and the
useState() Hook.
- Avoid direct mutation of state arrays.
- Use the spread operator to add items.
- Use
filter() to remove items.
- Use
map() to update items.
- Use
slice() for non-mutating array operations.
- Copy arrays before sorting or reversing.
- Update objects inside arrays without mutating them.
- Use functional state updates when appropriate.
- Build and test a complete to-do list application.
23. Conclusion
Updating arrays in state is an important React JS concept used in interactive applications. By creating new arrays instead of directly modifying existing state, developers can manage lists and collections more reliably.
Understanding the spread operator, map(), filter(), slice(), and functional state updates helps you build dynamic interfaces such as task managers, shopping carts, product lists, and registration systems.
24. React JS Training and Course Demo
Learn more about React JS, state management, component development, and practical application building through JustAcademy.
Course Link: JustAcademy React JS Training
Demo Registration: Register for React JS Course Demo