Avoiding Conditional Hooks
Learn about the alternate methods that developers can employ to avoid utilizing conditional hooks in their applications.
We'll cover the following...
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?
Press + to interact
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 beforehand:
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" propconst a = flag ? _a : ' 'return <h1>Hello World+{a}{b}</h1>}
Dynamic Title component with conditional hook usage
...