Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

What is the different between useImperativeHandle and useRef?

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading