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

269
Visualizações
Why would we useCallback in useIsMounted hook to return the ref from the hook?

In the following example taken from usehooks-ts website

import { useCallback, useEffect, useRef } from 'react'

function useIsMounted() {
  const isMounted = useRef(false)

  useEffect(() => {
    isMounted.current = true

    return () => {
      isMounted.current = false
    }
  }, [])

  return useCallback(() => isMounted.current, [])
}

export default useIsMounted

Why do we return the isMounted.current as a callback and don't return just the value isMounted.current?

What would be an example where returning just isMounted.current as a value will be a bad idea?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You could test the different implementation yourself to see what happens:

const UnmountingChild = ({ unmount }) => {
  const { isMounted, isMountedNC } = useIsMounted();

  useEffect(() => {
    console.log('IS MOUNTED BEFORE FETCH', isMounted()); // true
    console.log('IS MOUNTED NO CALLBACK BEFORE FETCH', isMountedNC.current); //true
    fetch('https://jsonplaceholder.typicode.com/todos/1').then((d) => {
      console.log('IS MOUNTED', isMounted()); //false
      console.log('IS MOUNTED NO CALLBACK', isMountedNC.current); //false
    });
    unmount(); // <-- This triggers the unmount of the component
  }, []);

  return <>Child</>;
};

function useIsMounted() {
  const isMounted = useRef(false);

  useEffect(() => {
    isMounted.current = true;
    return () => (isMounted.current = false);
  }, []);

  return {
    isMounted: useCallback(() => isMounted.current, []),
    isMountedNC: isMounted,
  };
}

Check the demo HERE

The usage of a callback is useful because it lets you to read directly the value of the ref with ref.current when needed , simply by calling isMounted(), if you want to directly return the ref you just have to make sure to return all the ref and not just ref.current because if you pass ref.current you will pass just the actual value and not the mutable ref object hence its value will always be stuck to false. Returning the ref forces you to then read every time the .current property, and that's not very nice, and it could mislead people using the hook without knowing the internal implementation, while calling isMounted() is nicer to read, and to use and avoids usage troubles.

about 4 years ago · Juan Pablo Isaza 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