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

144
Visualizações
How to call a function everytime my route changes? using useEffect hook

I'm working on a chat application and I want to make it like whenever user opens a chat it should show the latest chat.

So to do that I made a function scrollToBottom() that scroll to the bottom of the chat after 1 second, but I want to make it run, everytime the route changes. I tried placing router.query.id in useEffect dependency but it runs on every second automatically.

 useEffect(() => {
    setTimeout(() => {
      scrollToBottom();
    }, 1000);
 }, [router.query.id]);

So basically I want this useEffect to run only when router.query.id changes, that is only when the URL changes. How can I do that? Help would be appreciated.

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

0

You can use next/Router's inbuilt events to detect route change.

const scroll = () => {
  setTimeout(() => {
    scrollToBottom();
  }, 1000);
};

useEffect(() => {
  Router.events.on('routeChangeStart', scroll)

  // Remember to remove event listeners on unmount
  return () => {   
    Router.events.off('routeChangeStart', scroll);
  } 

}, []);
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