Menu

What Are Hooks? The Rules of Hooks

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

useStateStores data that changes over time
useEffectRuns code in response to rendering or data changes
useRefHolds a value or a DOM reference that survives re-renders
useContextReads shared data without passing props down manually
useMemoCaches a calculated value
useCallbackCaches 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

VA

Vishalini A



Learn via Video Course

React.js for Beginners: Build Modern Web Applications with React Logo

React.js for Beginners: Build Modern Web Applications with React

6 hrs



Get in Touch For Details