useState() HookHook State Management Functional Components
The useState() Hook lets you add state variables to React functional components. Whenever a state value changes, React automatically re-renders the component and shows the latest UI.
The basic syntax of useState() looks like this:
// Basic useState syntax pattern
const [state, setState] = useState(initialValue);
state – Current value of the state variable.setState – Function used to update that value.initialValue – Initial state (number, string, boolean, array, object, etc.).A simple counter that increments, decrements, and resets a numeric value using useState().
// Counter component using useState for a number
import React, { useState } from "react";
function Counter() {
const [count, setCount] = useState(0);
return (
<div className="text-center">
<h4>Count: {count}</h4>
<button
className="btn btn-primary me-2"
onClick={() => setCount(count + 1)}
>
+
</button>
<button
className="btn btn-danger me-2"
onClick={() => setCount(count - 1)}
>
-
</button>
<button
className="btn btn-secondary"
onClick={() => setCount(0)}
>
Reset
</button>
</div>
);
}
export default Counter;
setCount(count + 1) increases the value.setCount(count - 1) decreases the value.setCount(0) sets the counter back to 0.Here, a boolean state controls the greeting message and button style.
// Toggle login status using a boolean state
import React, { useState } from "react";
function Greeting() {
const [loggedIn, setLoggedIn] = useState(false);
return (
<div className="text-center mt-3">
<h5>{loggedIn ? "Welcome back!" : "Please log in"}</h5>
<button
className={`btn ${loggedIn ? "btn-danger" : "btn-success"}`}
onClick={() => setLoggedIn(!loggedIn)}
>
{loggedIn ? "Logout" : "Login"}
</button>
</div>
);
}
export default Greeting;
loggedIn is false → user sees “Please log in” and a green Login button.loggedIn becomes true → message changes to “Welcome back!” and the button turns red with text Logout.Use objects in state when related pieces of data belong together (like user profile info).
// Profile component storing an object in state
import React, { useState } from "react";
function Profile() {
const [user, setUser] = useState({ name: "John", age: 25 });
const updateAge = () => {
setUser({ ...user, age: user.age + 1 });
};
return (
<div className="text-center">
<h4>{user.name}, {user.age} years old</h4>
<button className="btn btn-info" onClick={updateAge}>
Increase Age
</button>
</div>
);
}
export default Profile;
{'{ name: "John", age: 25 }'}.updateAge(), which creates a new object.{'setUser({ ...user, age: user.age + 1 })'} copies all existing properties and only changes age.useStateWhen managing lists (like to-do items), store them as arrays in state and always create a new array when updating.
// Todo list component using an array in state
import React, { useState } from "react";
function TodoList() {
const [todos, setTodos] = useState(["Learn React", "Practice useState"]);
const addTodo = () => {
setTodos([...todos, "Build a project"]);
};
return (
<div>
<ul>
{todos.map((todo, i) => (
<li key={i}>{todo}</li>
))}
</ul>
<button
className="btn btn-outline-primary"
onClick={addTodo}
>
Add Todo
</button>
</div>
);
}
export default TodoList;
["Learn React", "Practice useState"]."Build a project" at the end.[...todos, "Build a project"] creates a new array (immutability preserved).If the new state depends on the previous state value, use the functional form of the updater. This guarantees React uses the most recent value, even when updates are batched.
// Step counter using functional updates
import React, { useState } from "react";
function StepCounter() {
const [step, setStep] = useState(0);
const increment = () => {
setStep((prev) => prev + 1);
};
return (
<div className="text-center">
<h5>Steps Taken: {step}</h5>
<button className="btn btn-primary" onClick={increment}>
Next Step
</button>
</div>
);
}
export default StepCounter;
setStep(step + 1) can sometimes use an outdated step value.setStep((prev) => prev + 1) always receives the latest value, making it safer.useState()useState calls for logically distinct pieces of data.(prev) => prev + 1 when the new value depends on the old one.state.push() or state.age++); always create a new array/object....user, ...todos) to copy existing data while updating only what changed.useEffect().useState for Celsius and Fahrenheit. Update the other value whenever one changes.Goal: Become comfortable declaring, updating, and reading state variables using useState() with numbers, strings, booleans, arrays, and objects.