Conditional Hook Calls with Ternaries
What you'll learn: Why ternary operators that conditionally call hooks still violate the Rules of Hooks, even though they feel like a clever workaround.
The Tempting Ternary Trap
You've learned that hooks can't go inside if statements. But what about ternary operators? They're expressions, not statements, so couldn't you write something like this?
const value = shouldUseEffect
? useEffect(() => { /* ... */ }, [])
: null;
This still violates the Rules of Hooks.
Why Ternaries Don't Escape the Rule
The issue isn't about syntax—it's about conditional execution. A ternary operator evaluates one branch or the other based on a condition. If shouldUseEffect is false today and true tomorrow, the hook doesn't get called on the first render but does get called on the second render.
This changes the number of hooks called between renders, breaking React's index-based hook tracking system. Remember: React relies on hooks being called in the exact same order, every single time, regardless of your component's state or props.
The Right Pattern
Conditionally use hook results, not hook calls:
const shouldRun = someCondition;
useEffect(() => {
if (shouldRun) {
// conditional logic inside
}
}, [shouldRun]);
The hook always gets called—you just control what it does based on your condition.
The Analogy
Think of React's hook system like taking attendance by seat number, not by name. Everyone must sit in the same seat every day. A ternary that skips calling a hook is like a student sometimes not showing up—React loses track of who's who.
Key Takeaway: Ternary operators that conditionally call hooks violate the Rules of Hooks just like if statements do—always call hooks unconditionally, then add conditional logic inside them.