useImperativeHandle function
Customizes the ref
value that is exposed to parent components when using uiForwardRef by setting Ref.current
to the return value of createHandle
.
In most cases, imperative code using refs should be avoided. For more information, see reactjs.org/docs/refs-and-the-dom.html#when-to-use-refs.
Note: there are two rules for using Hooks:
- Only call Hooks at the top level.
- Only call Hooks from inside the first argument of uiFunction.
Example:
mixin FancyInputProps on UiProps {
String? value;
late void Function(String) updater;
dynamic inputRef;
}
class FancyInputApi {
final void Function() focus;
FancyInputApi(this.focus);
}
UiFactory<FancyInputProps> FancyInput = uiForwardRef(
(props, ref) {
final localInputRef = useRef<InputElement>();
final inputRef = chainRefs(localInputRef, props.inputRef);
useImperativeHandle(ref,
() => FancyInputApi(() => localInputRef.current!.focus()),
/// Because the return value of [createHandle] never changes, it is not necessary for [ref.current]
/// to be re-set on each render so this dependency list is empty.
[],
);
return (Dom.input()
..ref = inputRef
..value = props.value
..onChange = (e) => props.updater(e.target.value as String)
)();
},
_$FancyInputConfig, // ignore: undefined_identifier
);
UiFactory<UseImperativeHandleExampleProps> UseImperativeHandleExample = uiFunction(
(props) {
final inputValue = useState('');
final fancyInputRef = useRef<FancyInputApi>();
return Fragment()(
(FancyInput()
..ref = fancyInputRef
..value = inputValue.value
..updater = inputValue.set
)(),
(Dom.button()
..onClick = (_) => fancyInputRef.current!.focus()
)('Focus Input'),
);
},
_$UseImperativeHandleExampleConfig, // ignore: undefined_identifier
);
Learn more: reactjs.org/docs/hooks-reference.html#useimperativehandle.
Implementation
void useImperativeHandle(dynamic ref, dynamic Function() createHandle, [List<dynamic>? dependencies]) =>
react_hooks.useImperativeHandle(ref, createHandle, dependencies);