Full Stack Development

useImperativeHandle

by Tomas Trescak t.trescak@westernsydney.edu.au

useImperativeHandle

Introduction

  • useImperativeHandle customises what child components expose via ref
  • Useful for reusable components like modals or custom inputs.
  • Works with React.forwardRef for ref forwarding

useImperativeHandle

Basic Syntax

  • Basic Syntax



  • Exposes custom methods or properties to the parent
    useImperativeHandle(ref, createHandle, [dependencies])
  
    useImperativeHandle(ref, () => ({
    focus: () => inputRef.current.focus(),
}));
  

useImperativeHandle

/

Example #1

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

const InputWithFocus = React.forwardRef((props, ref) => {
  const inputRef = useRef();

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

  return <input ref={inputRef} type="text" />;
}); 

function ParentComponent() {
  const inputRef = React.useRef();

  return (
    <div>
      <InputWithFocus ref={inputRef} />
      <button onClick={() => inputRef.current.focus()}>
        Focus Input
      </button>
    </div>
  );
}

render(<ParentComponent />)
    

useImperativeHandle

/

Example #2

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

const Modal = React.forwardRef((props, ref) => {
  const [isOpen, setIsOpen] = React.useState(false);

  React.useImperativeHandle(ref, () => ({
    open: () => setIsOpen(true),
    close: () => setIsOpen(false),
    toggle: () => setIsOpen((prev) => !prev),
  }));

  return isOpen ? (
    <div style={{ 
      border: "1px solid black", 
      padding: "1rem" 
    }}>
      <h2>Modal</h2>
      <button onClick={() => setIsOpen(false)}>
        Close
      </button>
    </div>
  ) : null;
});
    

useImperativeHandle

Usage

  • Use When
    • Customizing exposed behavior for reusable components.
    • Parent needs specific control over child actions.
  • Avoid When
    • Behavior can be achieved with props or callbacks.
    • Overcomplicating simple components.

useImperativeHandle

Summary

  • useImperativeHandle customizes the interaction between parent and child components via ref
  • Best for reusable components needing parent control.
  • Use sparingly to avoid complexity.

useImperativeHandle

Quiz