useImperativeHandle

Combining useRef, useImperativeHandle, and forwardRef enables the creation of custom input components with programmatically focused input methods. This approach offers a controlled and explicit means of interacting with a child component’s methods or properties from its parent.

Javascript




import React, {
    useRef,
    useImperativeHandle,
    forwardRef
} from 'react';
 
const ModifiedInputComponent = forwardRef((props, ref) => {
    const inputRef = useRef(null);
 
    // Expose the 'focusInput' method to the parent component
    useImperativeHandle(ref, () => ({
        focusInput: () => {
            inputRef.current.focus();
        }
    }));
 
    return (
        <input
            ref={inputRef}
            type="text"
            placeholder={props.placeholder}
        />
    );
});
 
export default ModifiedInputComponent;


Creating a reference to the input element in the child component is achieved using useRef. Subsequently, by utilizing useImperativeHandle, we expose a method named focusInput to the parent component via the ref. This mechanism empowers the parent component to invoke focusInput on the child component’s ref, facilitating programmatic focusing of the input element.

Javascript




import React, { useRef } from 'react';
import ModifiedInputComponent
    from './ModifiedInputComponent';
 
const ModifiedParentComponent = () => {
    const inputRef = useRef(null);
 
    const handleFocusButtonClick = () => {
        /*
        Call the 'focusInput' method of
        the child component
         */
        if (inputRef.current) {
            inputRef.current.focusInput();
        }
    };
 
    return (
        <div>
            {/* Child component with the ref */}
            <ModifiedInputComponent ref={inputRef}
                placeholder="Enter your name" />
            <button onClick={handleFocusButtonClick}>
                Focus Input
            </button>
        </div>
    );
};
 
export default ModifiedParentComponent;


Utilizing useRef in the parent component establishes a reference (inputRef) aimed at interacting with the focusInput method of the child component. Upon clicking the “Focus Input” button, the handleFocusButtonClick function executes. Within this function, the focusInput method is invoked on the child component’s ref, consequently focusing the input element.

This example showcases the collaborative use of useRef and useImperativeHandle to construct a more regulated interface for parent components to interact with child components.

How useRef Hook is useful in React ?

Hooks provides a way to useState and other React features in functional components without the need for class components. We can either use built-in hooks or customize and make our own. One of those hooks in useRef. It allows reference to a value that does not require rendering. It can be used to store a mutable value that does not cause a re-render when updated. It can be used to access a DOM element directly.

Table of Content

  • Primary Uses of useRef:
  • useImperativeHandle
  • Conclusion

Similar Reads

Primary Uses of useRef:

1. Accessing DOM elements...

useImperativeHandle:

...

Steps to Create a React App:

...

Conclusion:

...

Contact Us