October 16, 2022

React useImperativeHandle Hook With Examples

In this tutorial you'll learn about useImperativeHandle() hook in React.

Some background on forwardRef

As per React documentation useImperativeHandle should be used with forwardRef so some idea of forwardRef is required to understand useImperativeHandle hook.

When programming, it is an established norm that you should try to break your code into smaller units. React is no different and you try to break your code into several components, creating a hierarchy of parent and child components.

In React data flow is mostly unidirectional; from parent component to child component. This is done declaratively using props, using props you can pass data and handle to functions from parent to child component.

But the opposite is not true, parent component can't directly access data, call a method or access DOM nodes of the child component.

If you want to access DOM node of the child component from parent component you have to use forwardRef to give that capability to forward reference from parent to child component and then pass it further down to the required DOM node.

Read more about forwaredRef in this post- forwardRef in React With Examples

Here is the CustomInput component code that uses forwardRef

import { forwardRef } from "react";
const CustomInput = forwardRef((props, ref) =>{
    return (
        <div>
            <label htmlFor={props.id}>{props.label}</label>
            <input {...props} ref={ref}/>
        </div>
    );
});

export default CustomInput;

When to use useImperativeHandle hook

Using useImperativeHandle hook you can customize the exposed handle.

For example, take our CustomInput component, when you use forwardRef you are exposing the entire underlying <input> DOM node to the parent component.

Suppose you don’t want to do that; you just want to expose focus method of the <input> DOM node. For that you can use useImperativeHandle hook to expose a handle with only the methods that you want the parent component to call.

Syntax of useImperativeHandle hook

useImperativeHandle(ref, createHandle, dependencies?)

Parameters

ref- It is the same ref you receive as the second argument of component function.

createHandle- It is a function with no argument and returns the ref handle you want to expose. The returned ref handle may have any type. Usually, you will return an object with the methods you want to expose.

dependencies- This is an optional parameter. The list of all dependencies referenced inside of the createHandle code. Values included are props, state, and all the variables and functions declared directly inside your component body.

Here is the modified CustomInput component that exposes only the focus method. For that a function focusInput() is written that in turn calls the focus method of the <input>. This focusInput() function is exposed outside the component using the useImperativeHandle hook.

import { forwardRef, useImperativeHandle, useRef } from "react";

const CustomInput = forwardRef((props, ref) =>{
    const inputRef = useRef(null);
    const focusInput = () => {
        inputRef.current.focus(); 
    }
    useImperativeHandle(ref, () => {
        return {
            focus:focusInput,
        };
    }, []);
    return (
        <div>
            <label htmlFor={props.id}>{props.label}</label>
            <input  {...props} ref={inputRef}/>
        </div>
    );
});

export default CustomInput;

Here are some pointers about how useImperativeHandle is used in the above component.

1.Keep the real browser DOM in a separate ref which is passed as the second argument of the component function and the same ref is passed as the first argument of useImperativeHandle.

2. A function focusInput() is written that in turn calls the focus method of the DOM node <input>.

3. The second argument of the useImperativeHandle is a function that returns an object with the handle to the method focusInput() which we want to expose.

return {
    focus:focusInput,
};

Though here handle is named focus but you can use any name you want to use.

The parent component AddUser is same as written in this post- forwardRef in React With Examples

That's all for the topic React useImperativeHandle Hook With Examples. If something is missing or you have something to share about the topic please write a comment.


You may also like

No comments:

Post a Comment