What is the different between useImperativeHandle and useRef?
Asked Answered
G

3

5

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

Gluey answered 24/8, 2022 at 7:1 Comment(1)
I think your ref should have {} as initial value instead of null (2nd example), isn't it?Traumatize
G
4

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.

Gpo answered 24/8, 2022 at 7:8 Comment(1)
small comment: useImperativeHandle also has a dependency array, so you'd have to remove [] from useEffect for them to be similar (unless there are no other differences)Traumatize
B
2

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]);
Bridoon answered 24/8, 2022 at 9:2 Comment(0)
C
1

Ref The normal one let you control Dom, which is attached to the component

but useImperativeHandle Through it, it is possible to control the DOM and also other things, such as changing the internal state of the component or things that the normal ref cannot achieve like combining more than one process for more than one DOM through it like this example:

App Component

import { useRef } from 'react';
import Post from './Post.js';

export default function Page() {
  const postRef = useRef(null);

  function handleClick() {
    postRef.current.scrollAndFocusAddComment();
  }

  return (
    <>
      <button onClick={handleClick}>
        Write a comment
      </button>
      <Post ref={postRef} />
    </>
  );
}

post Component

import { forwardRef, useRef, useImperativeHandle } from 'react';
import CommentList from './CommentList.js';
import AddComment from './AddComment.js';

const Post = forwardRef((props, ref) => {
  const commentsRef = useRef(null);
  const addCommentRef = useRef(null);

  useImperativeHandle(ref, () => {
    return {
      scrollAndFocusAddComment() {
        commentsRef.current.scrollToBottom();
        addCommentRef.current.focus();
      }
    };
  }, []);

  return (
    <>
      <article>
        <p>Welcome to my blog!</p>
      </article>
      <CommentList ref={commentsRef} />
      <AddComment ref={addCommentRef} />
    </>
  );
});

export default Post;

commintList Component

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

const CommentList = forwardRef(function CommentList(props, ref) {
  const divRef = useRef(null);

  useImperativeHandle(ref, () => {
    return {
      scrollToBottom() {
        const node = divRef.current;
        node.scrollTop = node.scrollHeight;
      }
    };
  }, []);

  let comments = [];
  for (let i = 0; i < 50; i++) {
    comments.push(<p key={i}>Comment #{i}</p>);
  }

  return (
    <div className="CommentList" ref={divRef}>
      {comments}
    </div>
  );
});

export default CommentList;

addcomment Component

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

const AddComment = forwardRef(function AddComment(props, ref) {
  return <input placeholder="Add comment..." ref={ref} />;
});

export default AddComment;

see more here: useImperativeHandle

Chaplet answered 19/4 at 19:39 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.