Flutter Hooks with Riverpod: Less Boilerplate, Cleaner Widgets
flutter_hooks lets you keep a widget’s local state and setup/cleanup logic inside build, instead of spreading it across a StatefulWidget, a State class, initState and dispose. Paired with Riverpod through HookConsumerWidget, it’s how I write almost every screen in my Flutter apps.
I first wrote about hooks in 2021, coming from React. This is the updated version, based on how I use them now in Sundry, a production app with hook widgets in 76 files: useState appears in 53 files and useEffect in 33.
The problem hooks solve
A screen with a search field. With a StatefulWidget, you create the controller, add a listener, and remember to clean up both:
class SearchScreen extends StatefulWidget {
const SearchScreen({super.key});
@override
State<SearchScreen> createState() => _SearchScreenState();
}
class _SearchScreenState extends State<SearchScreen> {
final _controller = TextEditingController();
String _query = '';
@override
void initState() {
super.initState();
_controller.addListener(_onChanged);
}
void _onChanged() => setState(() => _query = _controller.text);
@override
void dispose() {
_controller.removeListener(_onChanged);
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) => /* ... uses _query ... */;
}
The same thing with hooks:
class SearchScreen extends HookWidget {
const SearchScreen({super.key});
@override
Widget build(BuildContext context) {
final controller = useTextEditingController();
final query = useState('');
useEffect(() {
void onChanged() => query.value = controller.text;
controller.addListener(onChanged);
return () => controller.removeListener(onChanged);
}, [controller]);
return /* ... uses query.value ... */;
}
}
One class instead of two. The controller disposes itself. The listener and its cleanup sit next to each other, so you can’t forget one.
The hooks I use most
| Hook | What it does | Replaces |
|---|---|---|
useState(initial) |
A ValueNotifier; setting .value rebuilds the widget |
A field + setState |
useEffect(fn, keys) |
Runs fn on first build and when keys change; the function it returns runs on cleanup |
initState, didUpdateWidget, dispose |
useMemoized(fn, keys) |
Creates a value once (or when keys change) and keeps it |
A late final field |
useTextEditingController() |
A controller that’s disposed for you | Controller + dispose |
useAnimationController() |
Same, with the ticker set up for you | SingleTickerProviderStateMixin + dispose |
useScrollController(), usePageController() |
Same idea for scrolling and pages | Controller + dispose |
useListenable(x) |
Rebuilds when a Listenable changes |
addListener + setState |
useFuture(future) |
Gives an AsyncSnapshot, like FutureBuilder |
FutureBuilder |
useRef(initial) |
A mutable box that doesn’t rebuild when changed | A plain field |
useOnAppLifecycleStateChange(fn) |
Called when the app is paused or resumed | WidgetsBindingObserver |
useEffect keys, the one thing to get right
useEffect(fn, const []): run once, on the first build. Cleanup on dispose.useEffect(fn, [a, b]): run on the first build and again wheneveraorbchanges (compared with==). The previous cleanup runs first.useEffect(fn)with no keys: run on every build. This is almost never what you want.
The function you pass returns either a cleanup function or null:
useEffect(() {
final sub = stream.listen(onEvent);
return sub.cancel; // cleanup
}, [stream]);
useEffect(() {
analytics.screenViewed('receipts');
return null; // nothing to clean up
}, const []);
The rules of hooks
- Only call hooks in
build, never in a callback such asonPressed. - Call them unconditionally, in the same order, every build. Flutter matches each hook to its saved state by call order.
if (x) useState(0)breaks every hook after it. - Name your own hooks
useSomething, so readers know the rules apply to them.
Hooks + Riverpod: HookConsumerWidget
With hooks_riverpod, one widget can use hooks and read providers:
class ReceiptArchiveScreen extends HookConsumerWidget {
const ReceiptArchiveScreen({super.key});
@override
Widget build(BuildContext context, WidgetRef ref) {
final receipts = ref.watch(receiptsProvider); // shared state
final filter = useState(const ReceiptsFilter()); // local UI state
final search = useTextEditingController();
useEffect(() {
void onChanged() => filter.value = filter.value.copyWith(search: search.text);
search.addListener(onChanged);
return () => search.removeListener(onChanged);
}, [search]);
// Load the full list once when the screen opens.
useEffect(() {
Future.microtask(() => ref.read(receiptsProvider.notifier).loadAll());
return null;
}, const []);
// ...
}
}
That’s a simplified version of a real screen in Sundry. The split I follow:
| Put it in a hook when… | Put it in a provider when… |
|---|---|
| Only this widget cares (a text field, a “saving” flag, an expanded panel) | Other screens need it, or it should survive leaving the screen |
| It dies with the screen | It comes from the network or a database |
| It’s a controller (text, animation, scroll) | It holds business logic you want to unit test |
If you’re not sure, start with a hook. Moving it into a provider later is easy.
For the provider side of this (code generation, async notifiers, testing), see Riverpod + Freezed + build_runner.
Why the Future.microtask?
useEffect runs during the build. Changing a provider’s state in the middle of a build throws an error in Riverpod (“Tried to modify a provider while the widget tree was building”). Wrapping the call in Future.microtask runs it right after the build finishes.
Write your own hooks
A custom hook is just a function that calls other hooks. This is where hooks beat StatefulWidget: you can share the logic without mixins or base classes.
A debounced value, useful for search fields that call an API:
T useDebounced<T>(T value, Duration delay) {
final debounced = useState(value);
useEffect(() {
final timer = Timer(delay, () => debounced.value = value);
return timer.cancel;
}, [value]);
return debounced.value;
}
// In a widget:
final text = useListenable(controller).text;
final query = useDebounced(text, const Duration(milliseconds: 300));
final results = ref.watch(searchProvider(query));
The search provider only runs 300 ms after the user stops typing, and the timer is cancelled automatically if the widget goes away.
Mistakes I see (and made)
- Missing keys in
useEffectoruseMemoized. The callback keeps using the old value of a variable. If it reads something that can change, put that thing in the keys. useMemoized(() => TextEditingController()). It works, but nothing disposes it. UseuseTextEditingController()and the other dedicated hooks.useStatefor values you can calculate. If it comes from other state, calculate it inbuild. Two copies of the same fact will drift apart.- Changing a provider directly inside
useEffect. See the microtask note above. - Hooks inside
if, loops orbuilder:callbacks. Pull the hook up to the top ofbuild, or move that part into its own widget.
When I don’t use hooks
- A team that doesn’t know them. Hooks are another concept to learn. On a client project, I match the team.
- Very simple widgets. A
StatelessWidgetorConsumerWidgetwith no local state needs nothing. - Inherited code. When I take over an existing app, I don’t rewrite working
StatefulWidgets just to switch styles.
Hooks and StatefulWidget mix fine in one app. Sundry still has plain StatefulWidgets in 16 files, next to the 76 that use hooks.
Takeaways
- Hooks put a widget’s state and its setup and cleanup in one place, and controllers dispose themselves.
- Get the
useEffectkeys right, and call hooks unconditionally at the top ofbuild. - Local, throwaway UI state goes in hooks. Shared state and business logic go in Riverpod providers.
- Custom hooks are the best part: reusable widget logic with no mixins.
Next: how to rebuild less with Provider’s Selector and Riverpod’s select, and the feature-first structure these widgets live in.