How to use useImperativeHandle to expose component methods

· Category: React

Short answer

useImperativeHandle customizes the instance value exposed when a parent uses ref on your component. It is typically paired with forwardRef.

Steps

  1. Accept a ref via forwardRef.
  2. Inside the component, call useImperativeHandle(ref, () => ({ ... })).
  3. Return an object containing only the methods or properties you want to expose.

Example

const FancyInput = forwardRef((props, ref) => {
  const inputRef = useRef(null);

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

  return <input ref={inputRef} {...props} />;
});

Tips

  • Expose the smallest surface area possible.
  • Prefer props over imperative APIs whenever you can.
  • Remember that refs should not hold reactive data; use state for that.