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.


useImperativeHandle(ref, createHandle, [deps])


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.


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
export default forwardRef(Button);


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

const App = () => {
   const btn = useRef(null);
   return (
         <button onClick={() => btn.current.blur()} ref={btn} />
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.


This will produce the following result.

Updated on 19-Mar-2021 10:50:36