Search⌘ K
AI Features

Avoiding Conditional Hooks

Explore techniques to properly handle conditional logic with React hooks by maintaining a fixed number and order of hook calls. This lesson teaches you how to restructure your code to avoid conditional hook calls, ensuring reliable state management and predictable component behavior.

Alternate and optimal approaches

So now we know that we shouldn't write any conditional hook statements, but how can we avoid it? Or, put another way, if we must implement some conditional logic involving hooks, what's the right way to do it?

The solution to this problem isn't difficult. We can still write conditional statements, just not conditional hook statements. As long as we have a fixed number of hooks and a consistent calling order, we can write the hook statement however we want.

Let's try to fix our examples, starting with setting a flag from T to F first. Instead of declaring _useHook conditionally, we can declare two of them ...

const Title = ({ flag }) => {
// Custom hook "_useHook" to get value 'a' and 'b'
const _a = _useHook('a')
const b = _useHook('b')
// Conditionally set the value of 'a' based on the "flag" prop
const a = flag ? _a : ' '
return <h1>Hello World+{a}{b}</h1>
}
Dynamic Title component with conditional hook usage
...