TechnicalEasy React

What are React hooks and what are the rules of hooks?

Asked for Frontend Developer, Full-Stack Developer, Mobile Developer

Why they ask this: Hooks are how modern React is written; breaking the rules causes hard-to-find bugs.

Answer

Hooks are functions that let function components use React features: useState (state), useEffect (side effects), useContext, useRef, useMemo, useCallback, and your own custom hooks (useSomething).

Rules of hooks:

  1. Call hooks only at the top level of a component or custom hook, never inside conditions, loops or nested functions. React identifies each hook by its call order.
  2. Call hooks only from React function components or custom hooks, not from regular functions.
jsx
function Profile({ userId }) {
  const [user, setUser] = useState(null);       // top level: OK
  // if (userId) { useEffect(...) }             // wrong: conditional hook
  useEffect(() => {
    if (!userId) return;                         // put the condition inside
    fetch(`/api/users/${userId}`).then((r) => r.json()).then(setUser);
  }, [userId]);
  return <p>{user?.name}</p>;
}

The eslint-plugin-react-hooks lint rules catch most mistakes.

Can you explain this in your own words?

Back to question bank