You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Describe what scenario you think is uncovered by the existing examples/articles
The README does a good job highlighting some of the footguns possible when using hooks. Specifically, it says to not use them in a conditional, but an implicit "conditional" exists: early returns. Consider the following:
classMainAppextendsHookWidget {
constMainApp({super.key});
@overrideWidgetbuild(BuildContext context) {
if (Random().nextBool()) {
returnContainer(
color:Colors.red,
child:constSizedBox(
height:100,
width:100,
),
);
}
useEffect(() {
print('useEffect');
returnnull;
}, []);
final counter =useState(0);
returnScaffold(
body:Center(
child:Column(
mainAxisAlignment:MainAxisAlignment.center,
children:<Widget>[
constText('You have pushed the button this many times:'),
Text(
'${counter.value}',
style:Theme.of(context).textTheme.headlineLarge,
),
],
),
),
floatingActionButton:FloatingActionButton(
onPressed: () => counter.value++,
tooltip:'Increment',
child:constIcon(Icons.add),
),
);
}
}
This code compiles and seems to run fine, but any time the "hooks codepath" is run (i.e useEffect prints), the counter is re-initialized to 0. If you move the hooks above the early return, things work correctly.
Describe why existing examples/articles do not cover this case
Don’t call Hooks inside loops, conditions, or nested functions. Instead, always use Hooks at the top level of your React function, before any early returns. You can only call Hooks while React is rendering a function component:
We can probably have more parity by calling out the same in the README.
The text was updated successfully, but these errors were encountered:
It's considered a feature. flutter_hooks does support early returns.
The state after an early return getting destroyed when reaching the early return makes sense generally. View it as releasing unused resources.
In the same sense, effects and controllers would be disposed.
Describe what scenario you think is uncovered by the existing examples/articles
The README does a good job highlighting some of the footguns possible when using hooks. Specifically, it says to not use them in a conditional, but an implicit "conditional" exists: early returns. Consider the following:
This code compiles and seems to run fine, but any time the "hooks codepath" is run (i.e
useEffect
prints), the counter is re-initialized to0
. If you move the hooks above the early return, things work correctly.Describe why existing examples/articles do not cover this case
The react hooks documentation calls out:
We can probably have more parity by calling out the same in the README.
The text was updated successfully, but these errors were encountered: