UseEffect constructor
UseEffect(
- Function callback,
- List<
ReactterState> dependencies, [ - Object? context
A ReactterHook that manages side-effect.
The side-effect logic into the callback function is executed
when dependencies of ReactterState argument has changes
or instance
trigger LifeCycle.didMount
event.
UseEffect(() {
print("Execute by state changed or 'didMount' event");
}, [state], this);
If the callback returns a function,
then UseEffect considers this as an effect cleanup
.
The effect cleanup
callback is executed, before callback is called
or context trigger LifeCycle.willUnmount
event:
UseEffect(() {
print("Execute by 'didMount' event");
return () {
print("Execute by 'willUnmount' event");
};
}, [], this);
RECOMMENDED: Use it on Object constructor:
class AppController {
late final state = UseState(false);
AppController() {
UseEffect(() {
print('state: ${state.value}');
}, [state], this);
Future.delayed(
const Duration(seconds: 1),
() {
state.value = !state.value;
},
);
}
}
If you need to execute the UseEffect's callback inmediately created, use dispatchEffect on context parameter:
UseEffect(
() => print("Prompt execution or state changed"),
[state],
UseEffect.dispatchEffect,
);
or use mixin DispatchEffect:
class AppController with DispatchEffect {
AppController() {
UseEffect(
() => print("Prompt execution or state changed"),
[state],
this,
);
}
}
If you not put instance on the context parameter, should to call dispose method to clear any UseEffect's events.
See also:
- ReactterState, it receives as dependencies.
Implementation
UseEffect(
this.callback,
this.dependencies, [
this.context,
]) {
_initialized = true;
if (context == null) {
_watchDependencies();
return;
}
if (context is DispatchEffect) {
_runCallbackAndWatchDependencies();
return;
}
if (ReactterZone.current != null) return;
final instance = _getInstance(context);
if (instance != null) {
attachTo(instance);
return;
}
_watchDependencies();
}