0

I've recently started learning Next.js and I've been faced with something strange. I have this simple code:

import {useRouter} from 'next/Router';
import {Profile} from '../../components/Profile';

const JobsListingPage = () => {
    const Router = useRouter();
    console.log(Router.query);

    return (
        <div>
            <h1>Job Listing Dynamic Page</h1>
            <Profile />
        </div>
    );
}

export default JobsListingPage;

It works well and I get the result in the console. The strange part is, this code gets executed 4 times on the client side. Why really? Two first time it's empty and two last times it contains the data. Is that normal or I'm doing something wrong?

enter image description here

Doesn't look like a normal lifecycle.

Martin AJ
  • 6,261
  • 8
  • 53
  • 111
  • 1
    the first `{}` is for the initial rendering for hydrating React on the client-side. `{slug}` logs and onwards are populating states for re-renderings. If you want to disable double invoking (causing 2 similar logs), you should check `StrictMode` in [this document](https://stackoverflow.com/questions/71905418/console-logdynamic-page-logging-twice-in-nextjs/71907321#71907321). If you find how to turn `StrictMode` off in Next.js, I have a similar answer [here](https://stackoverflow.com/questions/71905418/console-logdynamic-page-logging-twice-in-nextjs/71907321#71907321). – Nick Vu Oct 27 '22 at 15:17
  • 1
    Thank you!~~ Glad that I'm able to help :D – Nick Vu Oct 27 '22 at 15:27

1 Answers1

1

Adding a console in root level is not a good way to measure the component rendering cycles.

wrap this inside a useEffect and check whether it's still duplicating.

 const {query} = useRouter();  

 useEffect(() => {console.log(query)}, [query])

if this is only printing 2 consoles (first one empty) then component rendering fine

Sachila Ranawaka
  • 39,756
  • 7
  • 56
  • 80