useEffect function

void useEffect(
  1. dynamic sideEffect(), [
  2. List<Object?>? dependencies
])

Runs sideEffect after every completed render of a DartFunctionComponent.

If dependencies are given, sideEffect will only run if one of the dependencies have changed. sideEffect may return a cleanup function that is run before the component unmounts or re-renders.

Note: there are two rules for using Hooks:

Example:

UseEffectTestComponent(Map props) {
  final count = useState(1);
  final evenOdd = useState('even');

  useEffect(() {
    if (count.value % 2 == 0) {
      evenOdd.set('even');
    } else {
      evenOdd.set('odd');
    }
    return () {
      print('count is changing... do some cleanup if you need to');
    };

    // This dependency prevents the effect from running every time [evenOdd.value] changes.
  }, [count.value]);

  return react.div({}, [
    react.p({}, ['${count.value} is ${evenOdd.value}']),
    react.button({'onClick': (_) => count.set(count.value + 1)}, ['+']),
  ]);
}

See: reactjs.org/docs/hooks-effect.html#tip-optimizing-performance-by-skipping-effects.

Implementation

void useEffect(dynamic Function() sideEffect, [List<Object?>? dependencies]) {
  final wrappedSideEffect = allowInterop(() {
    final result = sideEffect();
    if (result is Function) {
      return allowInterop(result);
    }

    /// When no cleanup function is returned, [sideEffect] returns undefined.
    return jsUndefined;
  });

  return React.useEffect(wrappedSideEffect, dependencies);
}