useImperativeHandler Hooks

The useImperativeHandler hook is a feature in React that allows you to define custom imperative methods that can be called from parent components. It’s particularly useful when you need to expose specific functionalities of a child component to its parent in a controlled manner.

  • Defining Custom Methods: With useImperativeHandler, you can define custom functions inside a child component that the parent component can call directly. This is helpful when you want to encapsulate certain functionalities within the child component but still allow the parent to interact with them.
  • Controlled Exposures: Unlike traditional component methods, the methods defined using useImperativeHandler are exposed explicitly by the parent component. This means the parent has full control over when and how these methods are accessed, which can be crucial for maintaining a clear and predictable component interface.

Syntax:

useImperativeHandle(ref, createHandle, [deps])

Example: Below is an example of useImperativeHandler hooks.

Javascript




import React, {
    useRef
} from 'react';
 
const App = () => {
    const inputRef = useRef(null);
    return (
        <div>
            <Input onFocus={() =>
                inputRef.current.focus()}
                ref={inputRef} />
        </div>
    );
};
 
export default App;


Javascript




import React, {
    useRef,
    useImperativeHandle,
    forwardRef
} from 'react';
 
function Input(props, ref) {
    const btn = useRef();
    useImperativeHandle(ref, () => ({
        focus: () => {
            console.log('Input is in focus');
        },
    }));
    return <input ref={btn}
        {...props}
        placeholder="type here" />;
}
 
export default forwardRef(Input);


Output:

Output



Ref Hooks in React

Ref Hooks provide a way to access and interact with the DOM (Document Object Model) nodes directly within functional components. Before hooks, refs were primarily used in class components. However, with Ref Hooks, functional components can also take advantage of this capability, enhancing flexibility and simplifying code.

  • useRef is used to create mutable references that persist across renders in functional components.
  • useImperativeHandler customizes the instance value that is exposed when using ref with functional components.

We will discuss about the following types of Ref Hooks in React.

Table of Content

  • useRef Hooks
  • useImperativeHandler Hooks

Similar Reads

useRef Hooks:

The useRef hook is a feature in React that provides a way to access and interact with a DOM element or a React component instance directly. It returns a mutable ref object whose current property is initialized with the passed argument (initially undefined). The current property can then be modified to reference a DOM element or a component instance....

useImperativeHandler Hooks:

...