Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

166
Visualizações
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

about 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

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.

about 4 years ago · Santiago Trujillo Relatório

0

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]);
about 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda