How To Use useImperativeHandle Hook In React? See Example

The useImperativeHandle hook customizes the ref value exposed by a child component when using forwardRef.
It allows the parent to access specific functions or values.


Basic Syntax

useImperativeHandle(ref, () => ({
  // exposed methods
}), [dependencies]);

Example

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

const Child = forwardRef((props, ref) => {
  useImperativeHandle(ref, () => ({
    focusInput: () => {
      inputRef.current.focus();
    }
  }));
  
  const inputRef = React.useRef();
  return <input ref={inputRef} type="text" />;
});

function App() {
  const childRef = useRef();

  return (
    <div>
      <Child ref={childRef} />
      <button onClick={() => childRef.current.focusInput()}>Focus Input</button>
    </div>
  );
}

export default App;

✅ Parent calls focusInput to control child input.


Key Points

  • Must be used with forwardRef
  • Exposes custom instance values or methods to parent
  • Improves controlled child behavior
  • Dependencies array controls when values update

Conclusion

useImperativeHandle allows safe and controlled access to child component methods, enhancing flexibility in component interactions.


Citations

https://savanka.com/category/learn/react/
https://www.w3schools.com/REACT/DEFAULT.ASP

Leave a Comment

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *