State is a built-in concept in React used to store data that can change over time. When state updates, the component re-renders to show the latest values on the screen.
In modern React function components, state is managed using the useState Hook.
⚙️ Hook: useState()
useState is a React Hook that lets you add state to function components.setCount).useState Syntax & TheoryThe useState Hook returns an array with two elements:
// Basic useState syntax with a number state
const [count, setCount] = useState(0);
count → current state variable.setCount → function used to update the value.0 → initial state value.This component uses useState to keep track of a counter and provides buttons to increase, decrease, and reset the value.
// Counter component using the useState Hook
import { useState } from "react";
function Counter() {
const [count, setCount] = useState(0);
const increment = () => setCount(count + 1);
const decrement = () => setCount(count - 1);
const reset = () => setCount(0);
return (
<div>
<h2>Counter: {count}</h2>
<button onClick={increment}>➕ Increment</button>
<button onClick={decrement}>➖ Decrement</button>
<button onClick={reset}>? Reset</button>
</div>
);
}
export default Counter;
count is 0.setCount(count + 1) and increases the value.count back to 0.count appears on the screen.You can maintain multiple independent pieces of state in one component by calling useState multiple times.
// Managing multiple state variables in one component
function UserProfile() {
const [name, setName] = useState("Guest");
const [age, setAge] = useState(18);
return (
<div>
<h3>Name: {name}</h3>
<h3>Age: {age}</h3>
<button onClick={() => setName("Riya")}>Change Name</button>
<button onClick={() => setAge(age + 1)}>Increase Age</button>
</div>
);
}
name and age are two separate state variables.name or age changes.When working with objects or arrays, you should copy the existing data before changing it. The spread operator (...) is commonly used for this.
// Safely updating an object state using the spread operator
function Student() {
const [info, setInfo] = useState({ name: "Aman", marks: 80 });
const updateMarks = () => {
setInfo({ ...info, marks: info.marks + 5 });
};
return (
<div>
<p>Name: {info.name}</p>
<p>Marks: {info.marks}</p>
<button onClick={updateMarks}>Add 5 Marks</button>
</div>
);
}
info is an object with name and marks.{ ...info, marks: info.marks + 5 } copies the old object and updates only marks.useState() at the top level of your component (not inside loops, conditions, or nested functions).useState() hooks in a single component.userName, score, theme).count++ or info.marks = 90); always use the updater function like setCount() or setInfo().setCount(prev => prev + 1).CounterApp component with buttons to increase, decrease, and reset the count.theme that toggles between "Light" and "Dark".Goal: Understand how to manage state in function components using useState and how state updates trigger component re-renders dynamically.