October 2019
Intermediate to advanced
426 pages
11h 49m
English
The useImperativeHandle Hook can be used to customize instance values that are exposed to other components when pointing a ref to it. Doing this should be avoided as much as possible, however, as it tightly couples components together, which harms reusability.
The useImperativeHandle Hook has the following signature:
useImperativeHandle(ref, createHandle, [dependencies])
We can use this Hook to, for example, expose a focus function that other components can trigger via a ref to the component. This Hook should be used in combination with forwardRef as follows:
function FocusableInput (props, ref) { const inputRef = useRef() useImperativeHandle(ref, () => ({ focus: () => inputRef.current.focus() })) return <input ...Read now
Unlock full access