How to use the useImperativeHandle Hook in React?

The useImperativeHandle hook is used to customize the instance value that is exposed to parent components when using the forwardRef function in React. This hook allows you to customize the value that is returned when the parent component accesses the ref.

Here is a basic example of how to use the useImperativeHandle hook in React:

  1. Import the necessary dependencies:
import React, { forwardRef, useImperativeHandle, useRef } from 'react';
  1. Create a functional component that uses the forwardRef function:
const ChildComponent = forwardRef((props, ref) => { const inputRef = useRef(); useImperativeHandle(ref, () => ({ focus: () => { inputRef.current.focus(); } })); return <input ref={inputRef} />; });

In this example, we are creating a simple child component that contains an input element. We are using the useRef hook to create a reference to the input element. We then use the useImperativeHandle hook to customize the instance value that is returned to the parent component. In this case, we are exposing a focus method that allows the parent component to focus on the input element.

  1. Use the child component in a parent component:
const ParentComponent = () => { const childRef = useRef(); const handleFocus = () => { childRef.current.focus(); }; return ( <div> <ChildComponent ref={childRef} /> <button onClick={handleFocus}>Focus on Input</button> </div> ); };

In this example, we are using the ChildComponent in a ParentComponent and passing a ref to the ChildComponent. We can then call the focus method on the childRef to manually focus on the input element when the button is clicked.

This is a basic example of how to use the useImperativeHandle hook in React. It is a useful tool for customizing the instance value that is returned to parent components when using the forwardRef function.