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.

2
  • 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. If you find how to turn StrictMode off in Next.js, I have a similar answer here. Commented Oct 27, 2022 at 15:17
  • 1
    Thank you!~~ Glad that I'm able to help :D Commented Oct 27, 2022 at 15:27

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

5 Comments

Uncaught ReferenceError: Router is not defined
update console log console.log(query) @MartinAJ
Yeah, better i.sstatic.net/Px4Y9.png, thanks, upvoted
I did it like this export default React.memo(JobsListingPage);. Still 3 times.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.