What is the different between useImperativeHandle and useRef?

Viewed 95

As I understand, useImperativeHandle helps parent component able to call function of its children component. You can see a simple example below

const Parent = () => {
    const ref = useRef(null);
    const onClick = () => ref.current.focus();

    return <>
        <button onClick={onClick} />
        <FancyInput ref={ref} />
    </>
}

function FancyInput(props, ref) {
    const inputRef = useRef();
    useImperativeHandle(ref, () => ({
      focus: () => {
        inputRef.current.focus();
      }
    }));
    return <input ref={inputRef} />;
}

FancyInput = forwardRef(FancyInput);

but it can be easy achieved by using only useRef

const Parent = () => {
    const ref = useRef({});
    const onClick = () => ref.current.focus();

    return <>
        <button onClick={onClick} />
        <FancyInput ref={ref} />
    </>
}

function FancyInput(props, ref) {
    const inputRef = useRef();
    useEffect(() => {
        ref.current.focus = inputRef.current.focus
    }, [])
    return <input ref={inputRef} />;
}

FancyInput = forwardRef(FancyInput);

So what is the true goal of useImperativeHandle. Can someone give me some advices?. Thank you

2 Answers

Probably something similar to the relationship between useMemo and useCallback where useCallback(fn, deps) is equivalent to useMemo(() => fn, deps). Sometimes there is more than one way to accomplish a goal.

I'd say in the case of useImperativeHandle the code can be a bit more succinct/DRY when you need to expose out more than an single property.

Examples:

function FancyInput(props, ref) {
  const inputRef = useRef();
  useImperativeHandle(ref, () => ({
    focus: () => inputRef.current.focus(),
    property,
    anotherProperty,
    ... etc ...
  }), []); // use appropriate dependencies

  ...
}

vs

function FancyInput(props, ref) {
  const inputRef = useRef();
  useEffect(() => {
    ref.current.focus = inputRef.current.focus;
    ref.current.property = property;
    ref.current.anotherProperty = anotherProperty;
    ... etc ...
  }, []); // use appropriate dependencies

  ...
}

Not a big difference, but the useImperativeHandle is less code.

it can be easy achieved by using only useRef

No, you need at least another useEffect or probably better useLayoutEffect? And even then it does a teeny tiny bit more than your code.

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

is more likely equivalent to:

// using a function.
// no need to create this object over and over if there is no `ref`, 
// or no need to update the `ref`.
const createRef = () => ({
  focus: () => {
    inputRef.current.focus();
  }
});

useLayoutEffect(() => {
  // refs can be functions!
  if (typeof ref === "function") {
    ref(createRef());

    // when the ref changes, the old one is updated to `null`. 
    // Same on unmount.
    return () => {
      ref(null);
    }
  }

  // and the same thing again for ref-objects
  if (typeof ref === "object" && ref !== null && "current" in ref) {
    ref.current = createRef();

    return () => {
      ref.current = null;
    }
  }
}, [ref]);
Related