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

114
Visualizações
Can React class components leverage custom hooks which take an argument?

One way I know how to use hooks inside a class component is to have an HOC which returns a functional component, inside of which we can call the hook and pass the prop to a class component. Look at How can I use React hooks in React classic `class` component? and answer by Joel Cox.

Now coming to the question, taking the example from https://reactjs.org/docs/hooks-custom.html#using-a-custom-hook, consider we have a hook useFriendStatus which accepts a friendID, has an effect to subscribe to that online status of that friend and cleans up on every re-render, so that for a new friendID, the hook can subscribe to the new friendID.

function useFriendStatus(friendID) {
  const [isOnline, setIsOnline] = useState(null);

  // Effect to subscribe to online status of friendID and unsubscribe on re-render

  return isOnline;
}

Can a class component use such a hook? In the HOC pattern, we are leveraging the mount cycle of the hook. Can we leverage re-rendering of hooks in a React class component ?

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

0

You really should not use your hook in a Class component at all (and definitely not in componentDidMount lifecycle method - likely throws an error), but you also cannot use your custom Hook within the useEffect of a functional component (will throw a React error stating this if you try)... part of the purpose/utility of creating is larger so that you can abstract out data fetching or other async calls from other components.

(Those components can still have other useEffects if necessary but should not contain custom Hooks)

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