Clean • Professional
In React, state is a way to store and manage dynamic data in your components. The useState hook allows functional components to have state, making them powerful and interactive without needing class components.
The useState hook is a built-in React Hook that lets you:
It follows this syntax:
const [state, setState] = useState(initialValue);
state → Current value of the statesetState → Function to update the stateinitialValue → Default value of the stateExample – Counter Component
import React, { useState } from "react";
function Counter() {
const [count, setCount] = useState(0); // Initial state = 0
return (
<div>
<h1>Count: {count}</h1>
<button onClick={() => setCount(count + 1)}>Increment</button>
<button onClick={() => setCount(count - 1)}>Decrement</button>
</div>
);
}
export default Counter;
count is the state variablesetCount updates the stateuseStateTo use useState, import it from React at the top of your component:
import { useState } from "react";
Example – Favorite Color
import { useState } from "react";
import { createRoot } from "react-dom/client";
function FavoriteColor() {
const [color, setColor] = useState("red"); // Initial state = "red"
return (
<><h1>My favorite color is {color}!</h1>
<button type="button" onClick={() => setColor("blue")}>
Blue
</button>
</>
);
}
createRoot(document.getElementById("root")).render(
<FavoriteColor />
);
You can declare multiple useState hooks to track independent data:
function MyCar() {
const [brand, setBrand] = useState("Ford");
const [model, setModel] = useState("Mustang");
const [year, setYear] = useState("1964");
const [color, setColor] = useState("red");
return (
<><h1>My {brand}</h1>
<p>
It is a {color} {model} from {year}.
</p>
</>
);
}
Instead of multiple useState calls, you can track all values in a single object:
function MyCar() {
const [car, setCar] = useState({
brand: "Ford",
model: "Mustang",
year: "1964",
color: "red",
});
const updateColor = () => {
setCar(prevCar => ({ ...prevCar, color: "blue" }));
};
return (
<><h1>My {car.brand}</h1>
<p>
It is a {car.color} {car.model} from {car.year}.
</p>
<button onClick={updateColor}>Change Color</button>
</>
);
}
When the new state depends on the previous state, use a function inside setState:
This ensures accurate updates even when multiple state changes happen quickly.
setCount(prevCount => prevCount + 1);
The useState hook can store:
"Hello"42true or false[1, 2, 3]{ key: value }For example:
const [state, setState] = useState({
name: "Alice",
age: 25,
hobbies: ["reading", "gaming"],
isAdmin: true
});
useEffect