1. What is Component State?
While props are passed into a component from the outside, state represents data that is created, held, and modified inside the component over time. Whenever state updates, React automatically schedules a re-render to reflect the new data in the browser UI.
2. The useState Hook
Hooks are special functions that allow you to "hook into" React features without writing class components. The useState hook declares a state variable:
import { useState } from 'react';
function Counter() {
// Syntax: const [stateValue, stateUpdaterFunction] = useState(initialValue);
const [count, setCount] = useState(0);
return (
Current Question: {count}
);
}
3. Functional State Updates
If your new state depends on the previous state value, always pass an updater callback function to setState to avoid stale closure bugs during rapid updates:
// Recommended pattern when computing next state from previous state:
setCount(prevCount => prevCount + 1);
4. Managing Object State
When state is an object, calling the setter replaces the entire object. Use the spread operator (...) to copy existing properties while overriding specific fields:
function UserForm() {
const [profile, setProfile] = useState({
name: "Aman",
role: "Student",
theme: "light"
});
const toggleTheme = () => {
setProfile(prev => ({
...prev,
theme: prev.theme === "light" ? "dark" : "light"
}));
};
return (
Theme: {profile.theme}
);
}
5. Managing Array State
Never mutate arrays directly with push() or splice(). Instead, return a new array using the spread operator or filter():
function QuestionBookmarks() {
const [bookmarks, setBookmarks] = useState([1, 4, 7]);
// Adding an item immutably
const addBookmark = (questionNo) => {
setBookmarks(prev => [...prev, questionNo]);
};
// Removing an item immutably
const removeBookmark = (questionNo) => {
setBookmarks(prev => prev.filter(q => q !== questionNo));
};
}
6. Rules of Hooks
- Only call hooks at the top level: Never call hooks inside loops, conditions, or nested functions.
- Only call hooks from React function components or custom hooks.