How to add data into useState array in React?
Use the spread operator or functional updates to safely add new data into a useState array in React.
Advertisement
Question
How to add data into useState array in React?
Answer
State in React is immutable, so you can’t directly push into it.
Instead, use the spread operator to create a new array.
import { useState } from 'react';
function TodoList() {
const [todos, setTodos] = useState(['Learn React']);
const addTodo = () => {
setTodos([...todos, 'Build something cool']);
};
return (
<div>
<button onClick={addTodo}>Add Todo</button>
<ul>
{todos.map((t, i) => (
<li key={i}>{t}</li>
))}
</ul>
</div>
);
}
Alternatively, use a functional update if the next state depends on the previous one:
setTodos((prev) => [...prev, 'New Task']);
Real-World Example
Adding items to cart, notifications, chat messages, or lists.
Quick Practice
Build a list of notes that appends a new note every time you click “Add Note.”
Summary
Always create a new array when updating useState — React detects changes via new references.
Can I push directly into useState array?
No. That mutates the original state. Use the spread operator or functional update instead.
Advertisement
Stay Updated
Get the latest frontend challenges, interview questions and tutorials delivered to your inbox.
Advertisement