[Solution] useEffect not triggering in NextJS dynamic route

Felix Lee
2 min readNov 20, 2021

--

If you have been using dynamic route in NextJS, you may face this issue which useEffect is not triggering when the user is redirected to the same dynamic route. Let’s suppose we have our dynamic route as post/[id].tsx , a simple example would look something like this:

On first load, current route ID is 98, “13” is randomly generated in useEffect .

Notice the console does not print a second “USE EFFECT”, “Go to Post 13” button is not updated as well.

Solution 1: Add prop to useEffect dependency list

The first solution is straightforward, add the route query of the dynamic route(i.e id) to useEffect , like so:

Solution 2: Add key to getServerSideProps

Another way is to add a key that changes every time when the route changes to the props that returned from getServerSideProps . You can keep the useEffect dependency list as empty in this case

You can also find the code here.

--

--

Felix Lee

Software engineer in Singapore. Write random tech stuff. Still figuring out this “life” thing in life.