Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

143
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!