- Home
- Javascript
- What Are Hooks? The Rules of Hooks
What Are Hooks? The Rules of Hooks
Contents
React Hooks in Depth
What Are Hooks? The Rules of Hooks
What is a Hook?
A Hook is a function that lets a functional component use React features like state, side effects, and shared data. Every Hook's name starts with use.
You have already used one: useState.
Hook | What it does |
| useState | Stores data that changes over time |
| useEffect | Runs code in response to rendering or data changes |
| useRef | Holds a value or a DOM reference that survives re-renders |
| useContext | Reads shared data without passing props down manually |
| useMemo | Caches a calculated value |
| useCallback | Caches a function |
There are more, but these six cover almost everything a beginner needs.
Why is it Used?
Before Hooks (React 16.8 and earlier), only class components could hold state. Functional components were limited to displaying data. Hooks removed that split, and functional components became the standard.
The Rules of Hooks
There are two, and breaking them causes confusing bugs.
Rule 1: Only call Hooks at the top level of a component
Never inside an if, a loop, or a nested function.
jsx
// Wrong
function Profile({ isLoggedIn }) {
if (isLoggedIn) {
const [name, setName] = useState(""); // Conditional Hook
}
}
// Correct
function Profile({ isLoggedIn }) {
const [name, setName] = useState("");
if (isLoggedIn) {
// use name here
}
}React tracks Hooks by the order they are called. If that order changes between renders, React matches the wrong state to the wrong Hook.
Rule 2: Only call Hooks from React functions
Either a component, or a custom Hook. Never from a regular JavaScript function or an event handler.
jsx
// Wrong
function handleClick() {
const [count, setCount] = useState(0);
}Vite projects include an ESLint rule that warns you when you break either rule. Pay attention to those warnings.
ReactJS Tutorial
Vishalini A








