useImperativeHandle
External Documentation
void
useImperativeHandle<
Customizes the ref value that is exposed to parent components when using
forwardRef2 by setting ref.current to the return value of
createHandle.
In most cases, imperative code using refs should be avoided.
Note: there are two rules for using Hooks:
- Only call Hooks at the top level.
- Only call Hooks from inside a function component.
Example:
class FancyInputApi {
final void Function() focus;
FancyInputApi(this.focus);
}
final FancyInput = forwardRef2((props, ref) {
final inputRef = useRef<InputElement>(null);
useImperativeHandle(
ref,
() => FancyInputApi(() => inputRef.current?.focus()),
[],
);
return input({
'ref': inputRef.jsRef,
'value': props['value'],
});
});
Implementation
void useImperativeHandle<T>(
Object? ref,
T Function() createHandle, [
List<Object?>? dependencies,
]) {
JSAny? jsCreateHandle() => _toJsAny(createHandle());
// ref will be a JsRef in forwardRef2, or a Ref in forwardRef.
final jsRef = switch (ref) {
final Ref<Object?> r => r.jsRef,
final JsRef jr => jr,
final JSAny js => js,
_ => null,
};
final jsDeps = dependencies?.map(_toJsAny).toList().toJS;
_reactUseImperativeHandle(jsRef, jsCreateHandle.toJS, jsDeps);
}