useCallback

External Documentation

JSFunction useCallback(

  1. Function callback,
  2. List<Object?> dependencies
)

Returns a memoized version of callback that only changes if one of the dependencies has changed.

Note: there are two rules for using Hooks:

  • Only call Hooks at the top level.
  • Only call Hooks from inside a function component.

Example:

final MyComponent = registerFunctionComponent((props) {
  final count = useState(0);
  final delta = useState(1);

final increment = useCallback((_) { count.setWithUpdater((prev) => prev + delta.value); }, [delta.value]);

return div(children: [ pEl('Delta is ${delta.value}'), pEl('Count is ${count.value}'), button(text: 'Increment count', onClick: increment), ]); });

Implementation

JSFunction useCallback(Function callback, List<Object?> dependencies) {
  final jsCallback = switch (callback) {
    final void Function() fn => fn.toJS,
    final void Function(JSAny) fn => fn.toJS,
    _ => throw StateError('Unsupported callback type: ${callback.runtimeType}'),
  };

final jsDeps = dependencies.map(_toJsAny).toList().toJS; return React.useCallback(jsCallback, jsDeps); }