flutter_hooks in Flutter: solved exercise with useState and useEffect
flutter_hooks in Flutter: solved exercise with useState and useEffect
flutter_hooks brings React’s hooks pattern to Flutter. Instead of extending StatefulWidget + State, you extend HookWidget and call use* functions inside build. The result is less boilerplate and better reuse of stateful logic.
Problem statement
Implement three screens with flutter_hooks:
- Stopwatch:
useStatefor elapsed time,useEffectfor theTimer. - Reactive search:
useTextEditingController+useMemoizedto filter a list withoutStatefulWidget. - Custom hook: reusable
useCountdownfrom anyHookWidget.
Dependencies
Full solution
HookWidget vs StatefulWidget comparison
| Aspect | StatefulWidget | HookWidget |
|---|---|---|
| Boilerplate | createState(), State, dispose() | Just build() + use* calls |
| Logic reuse | Mixins or class extraction | Custom hook (pure function) |
| Resource cleanup | Manual dispose() | Return function from useEffect |
| Testability | Normal | Normal (same widget tests) |
| Learning curve | Low | Medium (must understand hook rules) |
Hook rules
- Only call hooks inside
HookWidget.build. - Never inside conditionals, loops, or callbacks.
- The call order must always be the same on every build.
Common mistakes
- Hook outside
HookWidget: throwsHookNotFoundError. Make sure to extendHookWidgetinstead ofStatelessWidget. - Empty dependencies with an effect that uses variables: if
useEffectcaptures a variable but its dependency list isconst [], the effect won’t re-run. Add the variable to the list. useMemoizedwith a mutable list: if you pass aListas a dependency, it compares by reference. Use primitive values or generate an explicit hash.
Practical use
flutter_hooks fits well in apps where you have many small StatefulWidgets with Timer, AnimationController, or TextEditingController. It eliminates manual dispose and reduces the bug surface from unreleased resources.
Recommended next exercise
- Implicit animations in Flutter: solved exercise
- AnimationController and Tween in Flutter: solved exercise
- All Flutter exercises
Guided practice and next step
FAQ
Is flutter_hooks compatible with Riverpod or BLoC?
Yes. There is hooks_riverpod that combines both packages. For BLoC, simply use HookWidget and access the BLoC via context.read/context.watch as normal.
Can I mix HookWidget with StatefulWidget in the same widget tree?
Yes, they are completely compatible. You can migrate screen by screen gradually.
Do hooks affect performance?
Not negatively. Internally they use the same mechanism as StatefulWidget. The resulting code is equivalent in performance but more compact.