Course contentsShow
← React
Lesson 1036 of 2,39626. Rules of Hooks Deep DiveFree lesson

Conditional Hooks in Development-Only Code

Understand why hooks in if (__DEV__) blocks may seem safe but still violate rules, and how to structure dev-only hooks correctly.

Conditional Hooks in Development-Only Code

You'll learn why even if (__DEV__) blocks can break the Rules of Hooks, and how to handle development-only hooks correctly.

When building React applications, you might want to add hooks that only run during development—for debugging, logging, or warnings. You might think wrapping them in if (__DEV__) makes them safe:

function MyComponent() {
  const [count, setCount] = useState(0);
  
  // ❌ STILL VIOLATES RULES!
  if (__DEV__) {
    useEffect(() => {
      console.log('Dev-only effect:', count);
    }, [count]);
  }
  
  return <button onClick={() => setCount(count + 1)}>{count}</button>;
}

The Problem

React doesn't know about your build tool's __DEV__ constant. From React's perspective, this is a conditional hook call. In development, React registers two hooks (useState + useEffect). When you build for production, it registers only one hook (useState). Different hook counts between environments breaks React's internal tracking.

Even worse: if your development build sometimes takes one branch and sometimes another based on runtime conditions, hook order becomes unpredictable.

The Correct Approach

Always call the hook unconditionally, but make its behavior conditional:

function MyComponent() {
  const [count, setCount] = useState(0);
  
  // ✅ Hook called unconditionally
  useEffect(() => {
    if (__DEV__) {
      console.log('Dev-only effect:', count);
    }
  }, [count]);
  
  return <button onClick={() => setCount(count + 1)}>{count}</button>;
}

In production builds, the minifier will strip the if (__DEV__) block entirely, leaving an empty effect that React can optimize away.

Key Takeaway: Conditional hook calls are always forbidden—even with build-time constants like __DEV__. Make the hook's logic conditional instead, and let your build tool optimize it away.