Introduction
Arrays are commonly used in React to store lists such as products, students, tasks, or users. When an array is stored in state, you should update it by creating a new array instead of directly changing the existing one. In this chapter, we will practice adding, removing, and updating array items using useState(), the spread operator, map(), and filter(). React js Updating Arrays in State practice questions with solutions help to understand the concepts.
1. How do you store an Array in React State?
You can use the useState() Hook to store an array in React state.
Solution:
import { useState } from "react";
function App() {
const [items, setItems] = useState(["Apple", "Mango", "Banana"]);
return (
<div>
{items.map((item) => (
<p key={item}>{item}</p>
))}
</div>
);
}
export default App;
Here, items contains the current array and setItems() is used to update it.
2. How do you Add an Item to an Array in React State?
Use the spread operator to create a new array containing the existing items and the new item.
Solution:
import { useState } from "react";
function App() {
const [items, setItems] = useState(["Apple", "Mango"]);
function addItem() {
setItems((currentItems) => [
...currentItems,
"Banana"
]);
}
return (
<div>
<button onClick={addItem}>Add Banana</button>
{items.map((item) => (
<p key={item}>{item}</p>
))}
</div>
);
}
export default App;
The spread operator copies the existing items into a new array.
[...currentItems, "Banana"]
This does not directly modify the previous state array.
3. How do you Add an Item at the Beginning of an Array?
You can place the new item before the spread elements.
Solution:
import { useState } from "react";
function App() {
const [items, setItems] = useState(["Mango", "Banana"]);
function addItem() {
setItems((currentItems) => [
"Apple",
...currentItems
]);
}
return (
<div>
<button onClick={addItem}>Add Apple</button>
{items.map((item) => (
<p key={item}>{item}</p>
))}
</div>
);
}
export default App;
The new array becomes:
Apple
Mango
Banana
The original state array is not directly changed.
4. How do you Remove an Item from an Array in React State?
The filter() method can create a new array without the item you want to remove.
Solution:
import { useState } from "react";
function App() {
const [items, setItems] = useState([
"Apple",
"Mango",
"Banana"
]);
function removeItem(itemToRemove) {
setItems((currentItems) =>
currentItems.filter((item) => item !== itemToRemove)
);
}
return (
<div>
{items.map((item) => (
<div key={item}>
<span>{item}</span>
<button onClick={() => removeItem(item)}>
Remove
</button>
</div>
))}
</div>
);
}
export default App;
For example, removing Mango produces:
Apple
Banana
filter() returns a new array and leaves the previous array unchanged.
5. How do you Update an Item inside an Array?
When you need to change an item, map() can create a new array while replacing only the required item.
Solution:
import { useState } from "react";
function App() {
const [items, setItems] = useState([
"Apple",
"Mango",
"Banana"
]);
function updateItem() {
setItems((currentItems) =>
currentItems.map((item) =>
item === "Mango" ? "Orange" : item
)
);
}
return (
<div>
<button onClick={updateItem}>
Change Mango to Orange
</button>
{items.map((item) => (
<p key={item}>{item}</p>
))}
</div>
);
}
export default App;
The result becomes:
Apple
Orange
Banana
map() returns a new array instead of modifying the existing state array.
6. How do you Update an Object inside an Array in React State?
Arrays often contain objects. You can use map() together with the object spread operator to update one object.
Solution:
import { useState } from "react";
function App() {
const [students, setStudents] = useState([
{ id: 1, name: "Rahul", marks: 70 },
{ id: 2, name: "Priya", marks: 80 }
]);
function updateMarks() {
setStudents((currentStudents) =>
currentStudents.map((student) =>
student.id === 1
? { ...student, marks: 85 }
: student
)
);
}
return (
<div>
<button onClick={updateMarks}>
Update Rahul's Marks
</button>
{students.map((student) => (
<p key={student.id}>
{student.name} - {student.marks}
</p>
))}
</div>
);
}
export default App;
The expression:
{ ...student, marks: 85 }
creates a new object while keeping the other properties unchanged.
7. How do you Add an Object to an Array in React State?
You can add a new object using the spread operator.
Solution:
import { useState } from "react";
function App() {
const [products, setProducts] = useState([
{ id: 1, name: "Laptop" },
{ id: 2, name: "Mobile" }
]);
function addProduct() {
const newProduct = {
id: 3,
name: "Headphones"
};
setProducts((currentProducts) => [
...currentProducts,
newProduct
]);
}
return (
<div>
<button onClick={addProduct}>
Add Product
</button>
{products.map((product) => (
<p key={product.id}>{product.name}</p>
))}
</div>
);
}
export default App;
The new product is added without directly changing the previous state array.
For dynamic applications, IDs should generally be stable and unique.
8. How do you Remove an Object from an Array using its ID?
Use filter() to keep every object except the one with the matching ID.
Solution:
import { useState } from "react";
function App() {
const [products, setProducts] = useState([
{ id: 1, name: "Laptop" },
{ id: 2, name: "Mobile" },
{ id: 3, name: "Headphones" }
]);
function removeProduct(id) {
setProducts((currentProducts) =>
currentProducts.filter(
(product) => product.id !== id
)
);
}
return (
<div>
{products.map((product) => (
<div key={product.id}>
<span>{product.name}</span>
<button
onClick={() => removeProduct(product.id)}
>
Remove
</button>
</div>
))}
</div>
);
}
export default App;
If the user removes product id: 2, only that product is removed.
9. Why Should You Avoid Directly Modifying an Array in React State?
You should avoid directly changing a state array because React state should be treated as immutable.
For example, avoid:
items.push("Orange");
setItems(items);
This changes the existing array.
Instead, create a new array:
setItems((currentItems) => [
...currentItems,
"Orange"
]);
For removing an item, prefer:
setItems((currentItems) =>
currentItems.filter((item) => item !== "Orange")
);
For updating an item, prefer:
setItems((currentItems) =>
currentItems.map((item) =>
item === "Apple" ? "Orange" : item
)
);
These approaches create new array references and make state updates easier for React to track.
10. How do you Build a Practical Todo List using Array State?
A Todo List is a common example of updating arrays in React. You can add, complete, and remove tasks.
Solution:
import { useState } from "react";
function TodoApp() {
const [todos, setTodos] = useState([
{ id: 1, text: "Learn React", completed: false },
{ id: 2, text: "Practice Hooks", completed: false }
]);
function addTodo() {
const newTodo = {
id: Date.now(),
text: "Build a React Project",
completed: false
};
setTodos((currentTodos) => [
...currentTodos,
newTodo
]);
}
function toggleTodo(id) {
setTodos((currentTodos) =>
currentTodos.map((todo) =>
todo.id === id
? { ...todo, completed: !todo.completed }
: todo
)
);
}
function removeTodo(id) {
setTodos((currentTodos) =>
currentTodos.filter((todo) => todo.id !== id)
);
}
return (
<div>
<h2>Todo List</h2>
<button onClick={addTodo}>
Add Todo
</button>
{todos.map((todo) => (
<div key={todo.id}>
<span>
{todo.text} -{" "}
{todo.completed ? "Completed" : "Pending"}
</span>
<button onClick={() => toggleTodo(todo.id)}>
Toggle
</button>
<button onClick={() => removeTodo(todo.id)}>
Remove
</button>
</div>
))}
</div>
);
}
export default TodoApp;
What this example demonstrates:
Add an item:
setTodos((currentTodos) => [
...currentTodos,
newTodo
]);
Update an item:
setTodos((currentTodos) =>
currentTodos.map((todo) =>
todo.id === id
? { ...todo, completed: !todo.completed }
: todo
)
);
Remove an item:
setTodos((currentTodos) =>
currentTodos.filter((todo) => todo.id !== id)
);
This pattern is useful for Todo Apps, Shopping Carts, Product Lists, Student Lists, and many other React applications.
Key Takeaways
- Use
useState()to store arrays in React state. - Do not directly modify an array stored in state.
- Use the spread operator to add items.
- Use
filter()to remove items. - Use
map()to update items. - Use
map()and object spread when updating objects inside an array. - Functional state updates are useful when the next state depends on the previous state.
- Stable unique IDs are useful for identifying list items and React keys.
- Creating a new array helps keep state updates predictable.
- Array state patterns are commonly used in Todo Lists, Product Lists, Shopping Carts, and dashboards.
FAQs
1. How do you update an array in React state?
Use the state setter to create a new array instead of directly modifying the existing array. Common methods include the spread operator, map(), and filter().
2. Can I use push() to add an item to a React state array?
You should not directly use push() on the existing state array. Instead, create a new array using the spread operator.
3. Which method is used to remove an item from a React array?
The filter() method is commonly used because it creates a new array containing only the items that should remain.
4. Which method is used to update an item in a React array?
The map() method is commonly used to create a new array while replacing the item that needs to change.
5. How do you update an object inside a React state array?
Use map() to find the required object and the object spread operator to create an updated object.
6. Why should React state arrays be treated as immutable?
Treating state as immutable helps avoid unintended mutations and makes state updates more predictable for React.
7. Should I use the array index when updating items?
An item’s stable unique ID is generally better for identifying and updating dynamic list items. Array indexes can become unreliable when items are inserted, removed, or reordered.
Written by Shubhranshu Shekhar, who has trained 20000+ students in coding.
