UseEffect.runOnInit constructor

UseEffect.runOnInit(
  1. Function callback,
  2. List<ReactterState> dependencies
)

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("Executed by state changed or 'didMount' event");
  },
  [state],
);

The callback function can return a cleanup function to manage the effect cleanup. The cleanup function is executed before the dependencies of ReactterState argument has changes or instance trigger LifeCycle.willUnmount event:

UseEffect(
  () {
    print("Executed by state changed or 'didMount' event");

    return () {
      print("Executed before state changed or 'willUnmount' event");
    };
  },
  [state],
);

RECOMMENDED: Use it on class constructor:

class AppController {
  final state = UseState(0);

  AppController() {
    UseEffect(
      () {
        print("Executed by state changed or 'didMount' event");

        return () {
          print("Executed before state changed or 'willUnmount' event");
        };
      },
      [state],
    );

    Timer.periodic(Duration(seconds: 1), (_) => state.value++);
  }
}

If you want to execute the effect on initialization, you can use UseEffect.runOnInit:

UseEffect.runOnInit(
  () {
    print("Executed on initialization and 'didMount' event");
  },
  [],
);

You can also use the DispatchEffect mixin to execute the effect on initialization:

class AppController with DispatchEffect {
  AppController() {
    UseEffect(
      () {
        print("Executed on initialization and 'didMount' event");
      },
      [],
    );
  }
}

Use bind method to bind the instance, if you want to execute the effect within the instance context:

UseEffect(
  () {
    print("Executed by `didMount` event of 'useController' instance");
  },
  [],
).bind(useController);

NOTE: A UseEffect instance can only be binded to one instance at a time. When create a new instance of UseEffect on the instance that is created by instance manager, this instance will be binded to it automatically.

NOTE: The UseEffect instance will be disposed automatically when the instance binded is destroyed by instance manager.

If the UseEffect instance didn't have an instance binded or the instance binded is not created by instance manager, you must dispose it manually, using the dispose method:

final useEffect = UseEffect(
  () {
    print("Executed by state changed");
  },
  [state],
);

[...]

useEffect.dispose();

See also:

Implementation

UseEffect.runOnInit(this.callback, this.dependencies) : super() {
  _runCallback(this, this);
  _isUpdating = false;
  _isDispatched = true;

  if (BindingZone.currentZone != null) return;

  _watchDependencies();
}