TExcelTAD
Home › React › What is a Hook?

What is a Hook?

Hooks are special functions that let function components "hook into" React features: remembering values between renders, running code after rendering, reading context, and more. Every hook's name starts with use — useState, useEffect, useContext — and you can write your own.

Before hooks (React 16.8), only class components could have state. Hooks made function components fully capable, and today they are how all new React code is written.

A first look

jsx · try it yourself
import { useState, useEffect } from 'react';

export default function App() {
  const [likes, setLikes] = useState(0);            // remember a value

  useEffect(() => {                                  // run code after rendering
    console.log(`Rendered with ${likes} likes`);
  }, [likes]);

  return (
    <button onClick={() => setLikes(likes + 1)} style={{ fontSize: 18 }}>
      ❤️ {likes}
    </button>
  );
}

A normal local variable (let likes = 0) would reset to 0 every time React calls the function. useState gives the component memory: React stores the value outside the function and hands it back on every render.

The built-in hooks

Hook Purpose Lesson
useState remember a value; changing it re-renders useState
useEffect synchronize with outside systems after render useEffect
useContext read a value provided higher up the tree useContext
useRef keep a mutable value or a DOM node without re-rendering useRef
useReducer manage complex state with a reducer function useReducer
useCallback keep the same function between renders useCallback
useMemo cache an expensive calculation useMemo
useTransition / useDeferredValue keep the UI responsive during heavy updates Transitions
useActionState / useOptimistic / use React 19 tools for actions and async data React 19 Actions
useId generate unique ids for accessibility attributes —

The two rules of hooks

Hooks rely on being called in the same order on every render — that's how React knows which stored value belongs to which useState call. So:

1. Only call hooks at the top level. Not inside conditions, loops, nested functions or after an early return.

jsx
function Profile({ user }) {
  if (!user) return null;
  const [tab, setTab] = useState('posts');   // ❌ skipped when user is null
}

function Profile({ user }) {
  const [tab, setTab] = useState('posts');   // ✅ always called
  if (!user) return null;
}

2. Only call hooks from React functions — function components or custom hooks. Not from regular JavaScript functions, class components or event handlers.

Tip: The eslint-plugin-react-hooks package (included in the Vite React template) catches both rule violations automatically.

Why order matters

React keeps a list of hook "slots" for each component instance. On every render it walks through your hook calls in order and matches them to the slots:

jsx · try it yourself
import { useState } from 'react';

export default function App() {
  const [name, setName] = useState('Kim');   // slot 1
  const [age, setAge] = useState(28);        // slot 2
  const [city, setCity] = useState('Hanoi'); // slot 3

  return (
    <div style={{ display: 'grid', gap: 6, width: 240 }}>
      <input value={name} onChange={(e) => setName(e.target.value)} />
      <input type="number" value={age} onChange={(e) => setAge(Number(e.target.value))} />
      <select value={city} onChange={(e) => setCity(e.target.value)}>
        <option>Hanoi</option>
        <option>Hue</option>
        <option>Saigon</option>
      </select>
      <p>{name}, {age}, lives in {city}</p>
    </div>
  );
}

If a condition skipped slot 2 on one render, city would receive the value stored in slot 2 — the age — and everything would be mixed up. That's why the rule exists.

Hooks are per component instance

Each rendered component has its own hook slots. Two <Toggle /> elements have independent state:

jsx · try it yourself
import { useState } from 'react';

function Toggle({ label }) {
  const [on, setOn] = useState(false);
  return (
    <label style={{ display: 'block', margin: 6 }}>
      <input type="checkbox" checked={on} onChange={() => setOn(!on)} /> {label}: {on ? 'ON' : 'off'}
    </label>
  );
}

export default function App() {
  return (
    <div>
      <Toggle label="Wi-Fi" />
      <Toggle label="Bluetooth" />
      <Toggle label="Airplane mode" />
    </div>
  );
}

Custom hooks

Because hooks are just functions, you can combine them into your own hook. A custom hook is a function whose name starts with use and that calls other hooks:

jsx · try it yourself
import { useState } from 'react';

function useCounter(start = 0, step = 1) {
  const [value, setValue] = useState(start);
  return {
    value,
    inc: () => setValue((v) => v + step),
    dec: () => setValue((v) => v - step),
    reset: () => setValue(start),
  };
}

export default function App() {
  const cups = useCounter(0);
  const score = useCounter(100, 10);
  return (
    <div>
      <p>☕ Cups today: {cups.value} <button onClick={cups.inc}>+</button> <button onClick={cups.dec}>−</button></p>
      <p>🏆 Score: {score.value} <button onClick={score.inc}>+10</button> <button onClick={score.reset}>reset</button></p>
    </div>
  );
}

The custom hook shares logic, not state: each call gets its own independent value. You'll build more in the Custom Hooks lesson.

Test yourself

Where may you call useState?

  1. Inside an if statement
  2. Inside a for loop
  3. At the top level of a function component
  4. Inside an event handler

Why must hooks be called in the same order on every render?

  1. For performance only
  2. React matches hook calls to stored state by their order
  3. JavaScript requires it
  4. Otherwise ESLint fails the build

What makes a function a custom hook?

  1. It is a class
  2. Its name starts with use and it calls other hooks
  3. It returns JSX
  4. It is exported from 'react'