ReactJS – useImperativeHandle hook

ReactJSWeb DevelopmentFront End Technology

In this article, we are going to see how to customize the instance value of the ref object.

Both useImperativeHandle and useRef hook allows to pass the ref object but the latter one doesn’t allow to customize the instances that are also passed with the ref object. useImperativeHandle hooks is different from the useRef hook in majorly two ways −

  • It allows handling and customizing the returned value explicitly.

  • It allows you to replace the native instances of the ref object with the user-defined ones.

Syntax

useImperativeHandle(ref, createHandle, [deps])

Example

In this example, we are going to build a custom Button Component that has a user-defined instance attached to the ref object.

Button component is the child component of the App component.

Button.js

import React, { useRef, useImperativeHandle, forwardRef } from 'react';

function Button(props, ref) {
   const btn = useRef();
   useImperativeHandle(ref, () => ({
      blur: () => {
         console.log('Custom Blur property is called');
      },
   }));
   return (
      <button ref={btn} {...props}>
         Click Here
      </button>
   );
}
export default forwardRef(Button);

App.jsx

import React, { useRef } from 'react';
import Button from './Button';

const App = () => {
   const btn = useRef(null);
   return (
      <div>
         <button onClick={() => btn.current.blur()} ref={btn} />
      </div>
   );
};
export default App;

When the 'Click Here' button is clicked, it calls the user-defined blur function which is attached to the passed ref object.

Output

This will produce the following result.

raja
Published on 19-Mar-2021 10:50:03
Advertisements