useImperativeHandle in React
Expert-Level Explanation
useImperativeHandle
is a hook used in conjunction withforwardRef
. It allows you to customise the instance value that is exposed to parent components when using refs. Essentially, it lets you control what aspects of a child component are exposed to parent components. This hook is used to give the parent components more control over the child components.
Creative Explanation
Imagine useImperativeHandle
as a customisable remote control for a robot (the child component). The manufacturer (child component) decides what buttons (functions and properties) are available on the remote control. However, through the parent componentuseImperativeHandle
, the user gets to customise some of these buttons according to their needs, enhancing interaction with the robot.
Practical Explanation with Code
Example of using useImperativeHandle
:
import React, { useRef, useImperativeHandle, forwardRef } from 'react';
function FancyInput(props, ref) {
const inputRef = useRef();
useImperativeHandle(ref, () => ({
focus: () => {
inputRef.current.focus();
}
}));
return <input ref={inputRef} />;
}
const FancyInputForwardRef = forwardRef(FancyInput);
function Parent() {
const inputRef = useRef();
return (
<>
<FancyInputForwardRef ref={inputRef} />
<button onClick={() => inputRef.current.focus()}>Focus the input</button>
</>
);
}
In this example,useImperativeHandle
is used to expose a focus
method to the parent component.
Real-World Example
In a complex form, a parent form component might need to control the focus or validation of its child input components. useImperativeHandle
can be used to expose these control functions to the parent, allowing it to manage focus or trigger validation from outside the child component.