DeployU
Interviews / Frontend Engineering / This component is crashing due to a 'Rules of Hooks' violation. How do you fix it?

Questions

This component is crashing due to a 'Rules of Hooks' violation. How do you fix it?

debugging Hooks & Patterns Interactive Quiz Code Examples
Wrong Approach

Maybe wrap useState in a try-catch to handle the error?

Right Approach

The useState is inside an if statement, which violates the Rules of Hooks. React relies on the call order of hooks being the same on every render. Conditional hooks break this:

The Rule: Don’t call Hooks inside loops, conditions, or nested functions.

Why It Matters: React tracks hooks by their call order. If a hook is called conditionally, the order changes between renders, corrupting React’s internal state tracking.

The Fix: Always call hooks at the top level. Use conditional logic after the hook call.

ConditionalCounter - Fix the Rules of Hooks Violation
Your Code
import React, { useState } from 'react';

export default function ConditionalCounter({ showCounter }) {
  // THE BUG: useState inside a condition!
  if (showCounter) {
    const [count, setCount] = useState(0); // This crashes!

    return (
      <div>
        <p>Count: {count}</p>
        <button onClick={() => setCount(count + 1)}>Increment</button>
      </div>
    );
  }

  return <p>Counter is hidden.</p>;
}

function App() {
  const [show, setShow] = useState(true);
  return (
    <div>
      <button onClick={() => setShow(!show)}>Toggle Counter</button>
      <ConditionalCounter showCounter={show} />
    </div>
  );
}
Click "Run Code" to see output...
Click "Run Code" to see test results...

The Solution

Option 1: Always call the hook, conditionally render the output

export default function ConditionalCounter({ showCounter }) {
  // Always call hooks at the top level
  const [count, setCount] = useState(0);

  if (!showCounter) {
    return <p>Counter is hidden.</p>;
  }

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={() => setCount(count + 1)}>Increment</button>
    </div>
  );
}

Option 2: Conditionally render the entire component

function Counter() {
  const [count, setCount] = useState(0);
  return <button onClick={() => setCount(c => c + 1)}>Count: {count}</button>;
}

function App() {
  const [show, setShow] = useState(true);
  return show ? <Counter /> : <p>Hidden</p>;
}

Practice Question

Which of the following is a valid rule for using React Hooks?