State With Arrays
Learn how to store arrays in React state, display list items, add new items, remove items, update array values, and follow immutable state update practices.
1. What Is State With Arrays?
An array is used to store multiple values in a single variable. In React, we can store an array in state when we need to manage a list of students, courses, tasks, or products.
For example, CIIT Training Institute can maintain a list of students enrolled in a React course.
const students = [
"SAMADHAN",
"SAMIKSHA",
"PRADNYA"
];
This array contains three student names. Using
useState(), we can store the array in React
state and update it when the list changes.
2. React Array State — Visual Diagram
The following diagram explains how React manages an array and updates the user interface when the array changes.
students
Add / Remove / Update
React renders the updated list
import { useState } from "react";
function StudentList() {
const [students, setStudents] = useState([
"SAMADHAN",
"SAMIKSHA",
"PRADNYA"
]);
return (
<div>
<h2>CIIT Student List</h2>
<p>Total Students: {students.length}</p>
</div>
);
}
export default StudentList;
students stores the current array,
setStudents updates it, and
students.length returns the number of items.
3. Creating an Array Using useState()
The useState() Hook allows a functional component
to store an array as state.
import { useState } from "react";
function StudentArray() {
const [students, setStudents] = useState([
"SAMADHAN",
"SAMIKSHA",
"PRADNYA"
]);
return (
<div>
<h2>CIIT Training Institute</h2>
<p>Total Students: {students.length}</p>
</div>
);
}
export default StudentArray;
Understanding the Code
-
useState()initializes the state with an array. -
studentscontains the current array. -
setStudentsis used to update the state. -
students.lengthgives the array's item count.
Expected Browser Output
CIIT Training Institute
Total Students: 3
4. Displaying Array Items Using map()
The map() method processes every array item and
returns a new array. In React, it is commonly used to render
a list of JSX elements.
import { useState } from "react";
function DisplayStudents() {
const [students] = useState([
"SAMADHAN",
"SAMIKSHA",
"PRADNYA"
]);
return (
<div>
<h2>CIIT Student List</h2>
<ul>
{students.map((student) => (
<li key={student}>{student}</li>
))}
</ul>
</div>
);
}
export default DisplayStudents;
How Does map() Work?
- React reads the array of students.
-
map()processes each student name. -
Each name is placed inside an
lielement. - React displays the resulting list in the browser.
Expected Browser Output
CIIT Student List
- SAMADHAN
- SAMIKSHA
- PRADNYA
key. In a real application, prefer a student ID
rather than a name if names may repeat or change.
5. Adding an Item to an Array
We can add a new item by creating a new array with the spread operator. The existing items are copied into the new array, followed by the new student.
import { useState } from "react";
function AddStudent() {
const [students, setStudents] = useState([
"SAMADHAN",
"SAMIKSHA",
"PRADNYA"
]);
function addStudent() {
setStudents((previousStudents) => [
...previousStudents,
"ROHAN"
]);
}
return (
<div>
<h2>CIIT Student List</h2>
<button onClick={addStudent}>
Add Student
</button>
<ul>
{students.map((student, index) => (
<li key={`${student}-${index}`}>
{student}
</li>
))}
</ul>
</div>
);
}
export default AddStudent;
Explanation
-
addStudent()runs when the button is clicked. -
previousStudentsrepresents the previous state supplied by React. -
...previousStudentscopies the existing items. -
"ROHAN"is added at the end of the new array. -
setStudents()schedules the state update.
SAMADHAN
SAMIKSHA
PRADNYA
Total: 3
SAMADHAN
SAMIKSHA
PRADNYA
ROHAN
Total: 4
6. Removing an Item Using filter()
The filter() method creates a new array containing
only the items that satisfy a condition. We can use it to
remove a student from a list.
import { useState } from "react";
function RemoveStudent() {
const [students, setStudents] = useState([
{ id: 1, name: "SAMADHAN" },
{ id: 2, name: "SAMIKSHA" },
{ id: 3, name: "PRADNYA" }
]);
function removeStudent(studentId) {
setStudents((previousStudents) =>
previousStudents.filter(
(student) => student.id !== studentId
)
);
}
return (
<div>
<h2>CIIT Student List</h2>
{students.map((student) => (
<div key={student.id} className="student-row">
<span>{student.name}</span>
<button
onClick={() => removeStudent(student.id)}
>
Remove
</button>
</div>
))}
</div>
);
}
export default RemoveStudent;
How Does It Work?
-
Each student has a unique
id. - Clicking Remove passes that student's ID to the function.
-
filter()keeps all students whose ID does not match the selected ID. - React renders the new array without the removed student.
SAMADHAN
SAMIKSHA
PRADNYA
SAMADHAN
PRADNYA
7. Updating an Item Using map()
We can use map() to update a specific item while
keeping the other items unchanged. For this example, each
student has a unique ID.
import { useState } from "react";
function UpdateStudent() {
const [students, setStudents] = useState([
{ id: 1, name: "SAMADHAN" },
{ id: 2, name: "SAMIKSHA" },
{ id: 3, name: "PRADNYA" }
]);
function updateStudent(studentId) {
setStudents((previousStudents) =>
previousStudents.map((student) =>
student.id === studentId
? {
...student,
name: student.name + " - React Student"
}
: student
)
);
}
return (
<div>
<h2>CIIT Student List</h2>
{students.map((student) => (
<div key={student.id} className="student-row">
<span>{student.name}</span>
<button
onClick={() => updateStudent(student.id)}
>
Update
</button>
</div>
))}
</div>
);
}
export default UpdateStudent;
Explanation
-
map()checks each student in the array. - If the ID matches, a new student object is created.
- The spread operator preserves the existing properties.
- If the ID does not match, the original student object is returned unchanged.
- SAMADHAN - React Student
- SAMIKSHA
- PRADNYA
8. Why Should We Avoid Mutating Arrays?
React state should be treated as read-only. Directly changing an existing state array can cause confusing behavior and prevents React from reliably detecting changes by reference.
students.push("ROHAN");
setStudents(students);
push() modifies the existing array.
setStudents((previous) => [
...previous,
"ROHAN"
]);
The spread operator creates a new array.
map()— transform or update items.filter()— remove items based on a condition.[...array, newItem]— append an item.[newItem, ...array]— add an item at the beginning.slice()— create a shallow copy of part of an array.
9. Common Mistakes
Modifying State with push()
Avoid:
students.push("ROHAN");
Use:
setStudents(previous => [...previous, "ROHAN"]);
Removing Items with splice()
Avoid:
students.splice(1, 1);
Use:
setStudents(previous =>
previous.filter(student => student.id !== 2)
);
Forgetting the key Attribute
Avoid:
students.map(student => <li>{student.name}</li>)
Use:
students.map(student => <li key={student.id}>{student.name}</li>)
Updating the Wrong Item
Use a unique ID to identify the item you want to update or remove. Array indexes can change when items are inserted, deleted, or reordered.
10. Practice Questions
- Create a React state array containing SAMADHAN, SAMIKSHA, and PRADNYA.
-
Display all student names using
map(). - Add a new student when a button is clicked.
-
Remove a selected student using
filter(). -
Update one student's name using
map(). -
Display the total number of students using
length. -
Explain why directly using
push()on a state array should be avoided.
Summary
React array state allows us to manage lists of students, courses, tasks, and products dynamically. The useState() Hook stores the array, map() helps display and update items, and filter() helps remove items. The spread operator creates a new array when adding elements. Always avoid directly mutating state arrays and use stable, unique keys when rendering lists. These practices help keep React state updates predictable and the user interface consistent.