State & Events
useState
State is a component's memory. When state changes, React re-renders the component with the new value.
Syntax:
const [value, setValue] = useState(initialValue);import { useState } from "react";
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>+1</button>
<button onClick={() => setCount(0)}>Reset</button>
</div>
);
}Updating arrays and objects
const [todos, setTodos] = useState([]);
setTodos([...todos, { id: Date.now(), text: "New task" }]); // add
setTodos(todos.filter((t) => t.id !== id)); // remove
const [user, setUser] = useState({ name: "Ali", age: 20 });
setUser({ ...user, age: 21 }); // update one field