← React Beginner Questions - Set 6 Q56

What is the purpose of the useImperativeHandle hook?

React Beginner Questions - Set 6

It lets a child decide what a forwarded ref exposes — a narrow API instead of the whole DOM node.

Example

import { forwardRef, useImperativeHandle, useRef, useState } from 'react';

const FancyInput = forwardRef(function FancyInput(props, ref) {
  const inputRef = useRef(null);
  const [value, setValue] = useState('');

  useImperativeHandle(ref, () => ({
    focus: () => inputRef.current.focus(),
    clear: () => { setValue(''); inputRef.current.focus(); },
    get length() { return value.length; },
  }), [value]);

  return <input ref={inputRef} value={value} onChange={e => setValue(e.target.value)} />;
});

// Parent
const ref = useRef(null);
ref.current?.clear();   // only these three members exist

What to notice

← Back to the question list