DEV Community

Cover image for ReactJS Hook Pattern ~UseImperativeHandle~
Ogasawara Kakeru
Ogasawara Kakeru

Posted on

ReactJS Hook Pattern ~UseImperativeHandle~

・useImperativeHandle allows child components to expose specific methods to their parent components through a ref. This pattern is useful when you need to call functions on a child component imperatively, like focusing an input. useImperativeHandle doesn't reveal entire DOM nodes, but reveals a specific method inside the focusInner method.

import { useRef, useImperativeHandle } from "react";

function CustomInput({ ref, ...rest }) {
  const localRef = useRef();

  useImperativeHandle(ref, () => ({
    focusInner: () => {
      localRef.current.focus();
    },
  }));

  return <input ref={localRef} {...rest} />;
}

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

  const handleFocus = () => {
    inputRef.current.focusInner()
  };

  return (
    <div>
      <h1>UseImperativeHandle</h1>

      <CustomInput ref={inputRef} placeholder="Click button to focus me" />
      <button onClick={handleFocus}>Focus Input</button>
    </div>
  );
}

export default App;


Enter fullscreen mode Exit fullscreen mode

Top comments (0)