The useState hook allows you to add state to your functional components β something only class components could do before React 16.8.
π Basic Example:
import { useState } from "react";
function Counter() {
const [count, setCount] = useState(0);
return (
<button onClick={() => setCount(count + 1)}>
Count: {count}
</button>
);
}
β¨ Key Points:
β’ useState returns [value, setter]
β’ Calling the setter (setCount) re-renders the component
β’ You can store any type: number, string, object, or array
π Example with Object:
const [user, setUser] = useState({ name: "Aman", age: 22 });
π Tip:
When updating state based on the previous value, always use the callback form:
setCount(prev => prev + 1);
useState is the foundation of all interactivity in React π
Top comments (0)