Skip to content

UseEffect

UseEffect is a hook that allows to manage side-effect, and its functionality is closely related to Lifecycle of the instance and its dependencies.

Syntax

UseEffect(
void | Function callback(),
List<ReactterState> dependencies,
);
// UseEffect run on init
UseEffect.runOnInit(
void | Function callback(),
List<ReactterState> dependencies,
);

UseEffect accepts these arguments:

  • callback : A function that performs side effects. This function is executed when the dependencies argument changes or the instance trigger Lifecycle.didMount event. If the callback returns a Function (considers as an effect cleanup), it will be called before the next effect is run or the instance trigger Lifecycle.willUnmount event.

  • dependencies: A list of state( ReactterState , learn about it here) that the effect depends on.

Properties & Methods

UseEffect provides the following properties and methods:

  • Methods inherited from ReactterState (Learn more here):

    • update : A method to notify changes after run a set of instructions.
    • refresh : A method to force to notify changes.
    • * bind : A method to bind an instance to it.
    • * unbind : A method to unbind an instance to it.
    • * dispose : A method to remove all listeners and free resources.

Usage

Declaration

UseEffect can be initialized using the constructor class, e.g.:

6 collapsed lines
1
class MyCounter {
2
final uCount = UseState(0);
3
4
const MyCounter() {
5
final timer = Timer.periodic(Duration(seconds: 1), (_) => uCount.value++);
6
7
UseEffect(() {
8
// Execute by `uCount` state changed or 'Lifecycle.didMount' event
9
print("Count: ${uCount.value}");
10
11
return () {
12
// Effect cleanup - Execute before `uCount` state changed or 'Lifecycle.willUnmount' event
13
if (uCount.value == 10 && timer.isActive) {
14
timer.cancel();
15
print("Counter stopped");
16
}
17
};
18
}, [uCount]);
2 collapsed lines
19
}
20
}

In the example above, the UseEffect hook is used to print the value of the uCount state every second and stop the timer when the value reaches 10 .

Running it inmediately

Sometime you may want to execute inmediately the UseEffect is initialized, you can use UseEffect.runOnInit to do that, e.g.:

3 collapsed lines
1
final uCount = UseState(0);
2
3
void main() {
4
UseEffect.runOnInit(() {
5
// Execute by `uCount` state changed or 'Lifecycle.didMount' event
6
print("Count: ${uCount.value}");
7
Future.delayed(const Duration(seconds: 1), () => uCount.value++);
8
9
return () {
10
// Effect cleanup - Execute before `uCount` state changed or 'Lifecycle.willUnmount' event
11
print("Cleanup executed");
12
};
13
}, [uCount]);
1 collapsed line
14
}

In the example above, the UseEffect.runOnInit hook is used to print the value of the uCount state inmediately and increment the value every second.