'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.



Solution 1:[1]

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);
  } 

}, []);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Madhan S