avoid-conditional-hooks
Warns when hooks inside the build method or other hooks are called conditionally.
Similar to State
, hooks are stored in the Element
of a Widget
. However, instead of having one State
, the Element
stores a List<Hook>
. Then in order to use a Hook
, one must call Hook.use
.
The hook returned by use
is based on the number of times it has been called. The first call returns the first hook; the second call returns the second hook, the third call returns the third hook and so on. Calling hooks conditionally breaks this implementation behavior and can lead to unexpected results.
Example
❌ Bad:
void useOtherFunction(bool condition) {
// LINT: Avoid conditional hooks. Try moving this invocation out of the condition.
final b = condition ? useMemoized(() {}) : useMemoized(() {});
}
class MyWidget extends HookWidget {
Widget build() {
var condition = true;
if (condition) {
useMemoized(() {}); // LINT: Avoid conditional hooks. Try moving this invocation out of the condition.
}
...
}
}
✅ Good:
class MyWidget extends HookWidget {
Widget build() {
useMemoized(() {
if (condition) {
...
}
});
...
}
}