Conditional Logic Around Hook Results, Not Calls
You'll learn the safe pattern for adding dynamic behavior with hooks: call unconditionally, then branch on the result.
The Safe Pattern for Dynamic Hook Behavior
When you need conditional logic involving hook data, you might be tempted to conditionally call the hook itself. Don't do that—it violates the rules of hooks. Instead, always call the hook at the top level, then use if statements or ternary operators on the result.
Why This Matters
Hooks must be called in the same order every render. If you wrap a hook call in a condition, React loses track of which hook is which, breaking its internal state management.
The Wrong Way
// ❌ NEVER DO THIS
function useUserData(shouldFetch) {
if (shouldFetch) {
const [data, setData] = useState(null); // Conditional hook call!
}
}
The Right Way
// ✅ Call hook unconditionally, then use the result conditionally
function useUserData(shouldFetch) {
const [data, setData] = useState(null);
useEffect(() => {
if (shouldFetch) { // Condition around the LOGIC, not the hook
fetchData().then(setData);
}
}, [shouldFetch]);
return shouldFetch ? data : null; // Condition on what you RETURN
}
The Mental Model
Think of hooks like attendance at a meeting—everyone must show up in the same order every time. What people do at the meeting can change based on conditions, but skipping the meeting entirely breaks the system.
Key Takeaway: Always call hooks unconditionally at the top level. Use if statements, ternary operators, and logical operators on the values returned from hooks, never around the hook calls themselves.