React
Beginner
1 min read
State with Objects and Arrays
Example
import { useState } from 'react';
// ── Object state ──────────────────────────────────────────────
function ProfileForm() {
const [profile, setProfile] = useState({ name: '', email: '', bio: '' });
// CORRECT: spread to create a new object
const updateField = (field, value) =>
setProfile(prev => ({ ...prev, [field]: value }));
return (
<form>
<input value={profile.name} onChange={e => updateField('name', e.target.value)} placeholder="Name" />
<input value={profile.email} onChange={e => updateField('email', e.target.value)} placeholder="Email" />
<textarea value={profile.bio} onChange={e => updateField('bio', e.target.value)} placeholder="Bio" />
<pre>{JSON.stringify(profile, null, 2)}</pre>
</form>
);
}
// ── Array state ───────────────────────────────────────────────
function TodoList() {
const [todos, setTodos] = useState([
{ id: 1, text: 'Learn React', done: false },
{ id: 2, text: 'Build a project', done: false },
]);
// Add
const addTodo = (text) =>
setTodos(prev => [...prev, { id: Date.now(), text, done: false }]);
// Toggle
const toggle = (id) =>
setTodos(prev => prev.map(t => t.id === id ? { ...t, done: !t.done } : t));
// Remove
const remove = (id) =>
setTodos(prev => prev.filter(t => t.id !== id));
return (
<ul>
{todos.map(todo => (
<li key={todo.id}>
<span style={{ textDecoration: todo.done ? 'line-through' : 'none' }}
onClick={() => toggle(todo.id)}>
{todo.text}
</span>
<button onClick={() => remove(todo.id)}>✕</button>
</li>
))}
</ul>
);
}
export default TodoList;