All topics

Next.js interview questions

12 questions with answers. 171 open jobs in India ask for Next.js.

  1. Why useEffect running twice and how to handle it well in React?

    useEffect being called twice on mount is normal since React version 18 when you are in development with StrictMode. Here is an overview of the reason from the doc:

    In the future, we’d like to add a feature that allows React to add and remove sections of the UI while preserving state. For example, when a user tabs away from a screen and back, React should be able to immediately show the previous screen. To do this, React will support remounting trees using the same component state used before unmounting.

    This feature will give React better performance out-of-the-box, but requires components to be resilient to effects being mounted and destroyed multiple times. Most effects will work without any changes, but some effects do not properly clean up subscriptions in the destroy callback, or implicitly assume they are only mounted or destroyed once.

    To help surface these issues, React 18 introduces a new development-only check to Strict Mode. This new check will automatically unmount and remount every component, whenever a component mounts for the first time, restoring the previous state on the second mount.

    This only applies to development mode, production behavior is unchanged.

    It seems weird, but in the end, it's so we write better React code, bug-free, aligned with current guidelines, and compatible with future versions, by caching HTTP requests, and using the cleanup function whenever having two calls is an issue. Here is an example:

    /* Having a setInterval inside an useEffect: */
    import { useEffect, useState } from "react";
    const Counter = () => {
      const [count, setCount] = useState(0);
      useEffect(() => {
        const id = setInterval(() => setCount((count) => count + 1), 1000);
        /* 
           Make sure I clear the interval when the component is unmounted,
           otherwise, I get weird behavior with StrictMode, 
           helps prevent memory leak issues.
        */
        return () => clearInterval(id);
      }, []);
      return <div>{count}</div>;
    };
    export default Counter;
    

    In this very detailed article, React team explains useEffect as never before and says about an example:

    This illustrates that if remounting breaks the logic of your application, this usually uncovers existing bugs. From the user’s perspective, visiting a page shouldn’t be different from visiting it, clicking a link, and then pressing Back. React verifies that your components don’t break this principle by remounting them once in development.

    For your specific use case, you can leave it as it's without any concern. And you shouldn't try to use those technics with useRef and if statements in useEffect to make it fire once, or remove StrictMode, because as you can read on the doc:

    React intentionally remounts your components in development to help you find bugs. The right question isn’t “how to run an Effect once”, but “how to fix my Effect so that it works after remounting”.

    Usually, the answer is to implement the cleanup function. The cleanup function should stop or undo whatever the Effect was doing. The rule of thumb is that the user shouldn’t be able to distinguish between the Effect running once (as in production) and a setup → cleanup → setup sequence (as you’d see in development).

    Read the rest at the sourceFrom Stack Overflow: asked by hossein fti, answered by Youssouf Oumar (CC BY-SA 4.0)

  2. Is using Redux with Next.js an anti-pattern?

    If you have a custom App with getInitialProps then the Automatic Static Optimization that Next.js provides will be disabled for all pages.

    True, if you follow this approach.

    Is there a better way ?

    Yes, you can create a Redux Provider as a wrapper and wrap the component you need, the redux context will be automatically initialized and provided within that component.

    Example:

    const IndexPage = () => {
      // Implementation
      const dispatch = useDispatch()
      // ...
      // ...
      return <Something />;
    }
    IndexPage.getInitialProps = ({ reduxStore }) => {
      // Implementation
      const { dispatch } = reduxStore;
      // ...
      // ...
    }
    export default withRedux(IndexPage)
    

    You have now the possibility to use Redux only for the pages which need state management without disabling the optimization for the entire App.

    Answering you question "Is using Redux with Next.js an anti-pattern?"

    No, but it needs to be used properly.

    More info on how is done here: https://github.com/vercel/next.js/tree/canary/examples/with-redux

    I hope this helps

    From Stack Overflow: asked by Jamie S, answered by ddon-90 (CC BY-SA 4.0)

  3. What is the difference between Next.js and Create React App?

    I've used both NextJs and CRA. Both these frameworks can be used to get started quickly and provide a good developer experience. However, both of these have use cases where either of them shines better. I'll try to compare them based on some of these factors. Feel free to suggest edits with additional points or comments

    Server Side Rendering

    CRA Next.js
    CRA doesn't support SSR out of the box.
    However, you can still configure it.
    It just takes more effort to setup SSR with your preferred server and configuration. The development team doesn't have plans to support this in the near future. They suggest other tools for this use case.
    NextJs has different types for SSR. It supports SSR out of the box.
    * Static generation: fetch data at build time. This works best for use cases like blogs or static websites
    * Server side rendering: fetch data and render for each requests. You have to do this when you need to serve different view for different users.

    Configurability

    I think this is point where these tools are very different and your decision can depend on this factor

    CRA Next.js
    Create React App doesn't leave you a lot of room to configure it.
    Configurations like webpack config cannot be changed unless
    you stray away from normal CRA way (eject, rescripts, rewired, craco).
    Basically, you have to use what's configured in
    react-scripts which is the core of CRA.
    Almost everything is configurable.
    If you check the example NextJs templates, you can see files like
    babelrc, jest.config, eslintrc etc
    that you can configure.

    Maintainability

    CRA Next.js
    CRA is very opinionated.
    If you keep updated with the releases of CRA, it's not hard to maintain.
    NextJs is also well maintained. They release regular updates.

    Typescript

    CRA Next.js
    Supports out of the box. You can initialize CRA app with typescript with
    npx create-react-app my-app --template typescript
    Supports typescript out of the box.
    Start with configurations for typescript with touch tsconfig.json

    Hooks support

    Latest version of both CRA and NextJs installs a version of React that supports hooks. You can also upgrade to the latest version easily

    Redux support

    Redux is a library that you can use with both these tools.

    From Stack Overflow: asked by DevLoverUmar, answered by sudo bangbang (CC BY-SA 4.0)

  4. What is different between App Router and Pages Router in Next.js?

    To easily understand it, I have created the below table of difference.
    Based on your requirements, you can choose the desired router.

    Feature App Router Pages Router
    Routing type Server-centric Client-side
    Support for Server Components Yes No
    Complexity More complex Simpler
    Performance Better Worse
    Flexibility More flexible Less flexible

    App Router is the newer router that supports new React features like Server Components.

    The official documentation recommends migrating to App Router to get React's latest features.

    From Stack Overflow: asked by Ragu, answered by krishnaacharyaa (CC BY-SA 4.0)

  5. NextJS 13 folder structure best practice

    I think reading this section in Next docs helps you organize the project folders:

    https://nextjs.org/docs/app/building-your-application/routing/colocation

    I tried with many different structures and I finally chose this one:

    1. Everything (all folders and files) will be in the /app directory because the /app directory accepts colocation and it’s different from /pages directory which was only for routing purposes. In this way /app directory can be assumed the new /src directory.

    2. All the non-routes folders will be Private Folders by prefixing their name with an underscore (as stated in the link above). This tells the Next router that this folder is not part of the routes. (e.g. _components, _libs, ...)

    3. To this point we established that every folder with underscore _ is not route and other folders without it are a part of the routing system (although having a page.tsx or page.js file in the folder is another condition for being a part of the routing system), but I used another Next 13 feature and it is Route Groups (as stated in the link above). It is wrapping a folder name in parenthesis, so that it shows the folder is for organizational purposes (grouping folders) and should not be included in the route’s URL path, e.g. (routes).

    With these principles, I have all my required folders in /app directory, and with Route Groups all my routes are grouped in a (routes) folder, and with Private Folders by prefixing non-route folders with underscore, everything is isolated.

    The image below is the summary of all the points above.

    Hope the link and my way of organizing project folders help you.

    From Stack Overflow: asked by Dead, answered by Mahmoud Taghinia (CC BY-SA 4.0)

  6. Is this Next.JS folder structure recommended?

    Stumbled upon this post while searching for a suitable folder structure for NextJS myself. I've been using a similar structure but recently found that this is not how you're suppose to use NextJS.

    I don't know too much about the details, but NextJS has optimizations at the page level. When you build a NextJS project, you will see the pages logged as part of the build. NextJS treats every component file under the pages folder as a page, so by placing non-page components in the pages folder, you are drastically increasing build time because now NextJS goes and builds every one of those components as a page.

    From Stack Overflow: asked by cross19xx, answered by user2545003 (CC BY-SA 4.0)

  7. Next.JS "Link" vs "router.push()" vs "a" tag

    router.push

    router.push('/push') behaves similarly to window.location. It does not create a <a> tag, which means - if you are concern with SEO, your links will not be detected by crawlers.

    <Link>

    However, <Link> will create a <a> tag, which means your links will be detected when crawlers scrape your site. End users will still navigate without reloading the page, creating the behavior of a Single Page App.

    <a>

    <a> tag without using next/link's <Link> creates a standard hyperlink which directs end user to the url as a new page. (standard behavior).

    You should be using <Link> throughout all your website, and use router.push for places where you need redirect in order to retain the behaviour of a Single Page App.

    From Stack Overflow: asked by PHRYTE, answered by Someone Special (CC BY-SA 4.0)

  8. What's the right way to float right or left using the material-ui appbar with material-ui-next?

    @Kyle You had it right :)

    just add to the grid container:

    justify="space-between"

    With your example:

    <AppBar position="static">
      <Toolbar>
        <Grid
          justify="space-between" // Add it here :)
          container 
          spacing={24}
        >
          <Grid item>
            <Typography type="title" color="inherit">
              Title
            </Typography>
          </Grid>
          <Grid item>
            <div>
              <HeartIcon />
              <Button raised color="accent">
                Login
              </Button>
            </div>
          </Grid>
        </Grid>
      </Toolbar>
    </AppBar>
    

    From Stack Overflow: asked by Kyle Pennell, answered by Idan Dagan (CC BY-SA 4.0)

  9. How to Set port in next.js?

    This work for me:

    "scripts": { 
        "dev": "next dev -p 8080",
        "start": "next start -p 8080",
    },
    

    From Stack Overflow: asked by Sohail Ahmad, answered by Sohail Ahmad (CC BY-SA 4.0)

  10. How can I get (query string) parameters from the URL in Next.js?

    Use router-hook.

    You can use the useRouter hook in any component in your application.

    https://nextjs.org/docs/api-reference/next/router#userouter

    pass Param

    import Link from "next/link";
    <Link href={{ pathname: '/search', query: { keyword: 'this way' } }}><a>path</a></Link>
    

    Or

    import Router from 'next/router'
    Router.push({
        pathname: '/search',
        query: { keyword: 'this way' },
    })
    

    In Component

    import { useRouter } from 'next/router'
    export default () => {
        const router = useRouter()
        console.log(router.query);
        ...
    }
    

    From Stack Overflow: asked by Sour LeangChhean, answered by junho (CC BY-SA 4.0)

  11. Next.js Redirect from / to another page

    Update: Next.js >= 13 with AppDir enabled
    You can use next/navigation to redirect both in client components and server components.

    Ex. in pages :

    import { redirect } from 'next/navigation';
    export default async function Home({ params }) {
        redirect('/hello-nextjs');
      // ...
    }
    

    Ex. In client components:

    'use client';
    import { useEffect } from 'react';
    import { useRouter } from 'next/navigation';
    export const Home= () => {
      const { push } = useRouter();
      useEffect(() => {
         push('/hello-nextjs');
      }, []);
      return <p></p>;
    };
    

    Update: Next.js >= 12.1
    As @warfield pointed out in his answer from next.js >= 12.1 relative URLs are no longer allowed in redirects and using them will throw an error. I'm reposting here his answer for more visibility :

    To redirect using middleware with Next.js >= 12.1:

    1. Create a middleware.ts (or .js) file at the same level as your pages directory
    2. Export a middleware function
    3. Create an absolute URL and pass it to redirect

    TypeScript example middleware.ts:

    
    import { NextResponse } from 'next/server'
    import type { NextRequest } from 'next/server'
    export function middleware(request: NextRequest) {   
      const url = request.nextUrl.clone()   
      if (url.pathname === '/') {
        url.pathname = '/hello-nextjs'
        return NextResponse.redirect(url)   
      } 
    }
    

    Update: Next.js >= 12
    Now you can do redirects using middleware, create a _middleware.js file inside the pages folder (or any sub folder inside pages)

    import { NextResponse, NextRequest } from 'next/server'
    export async function middleware(req, ev) {
        const { pathname } = req.nextUrl
        if (pathname == '/') {
            return NextResponse.redirect('/hello-nextjs')
        }
        return NextResponse.next()
    }
    

    Update: Next.js >= 10

    From Next.js 10 you can do server side redirects (see below for client side redirects) with a redirect key inside getServerSideProps or getStaticProps :

    export async function getServerSideProps(context) {
      const res = await fetch(`https://.../data`)
      const data = await res.json()
      // or use context.resolvedUrl for conditional redirect
      // if(context.resolvedUrl == "/")
      if (!data) {
        return {
          redirect: {
            destination: '/hello-nextjs',
            permanent: false,
          },
        }
      }
      return {
        props: {}, // will be passed to the page component as props
      }
    }
    

    Note : Using getServerSideProps will force the app to SSR,also redirecting at build-time is not supported , If the redirects are known at build-time you can add those inside next.config.js

    In next.js you can redirect after the page is loaded using Router ex :

    import Router from 'next/router'
    componentDidMount(){
        const {pathname} = Router
        if(pathname == '/' ){
           Router.push('/hello-nextjs')
        }
    }
    

    Or with Hooks :

    import React, { useEffect } from "react";
    import Router from 'next/router'
    ...
    useEffect(() => {
       const {pathname} = Router
       if(pathname == '/' ){
           Router.push('/hello-nextjs')
       }
     });
    

    If you want to prevent the flashing before the redirect you can use a simple trick :

    Read the rest at the sourceFrom Stack Overflow: asked by Arthur, answered by Nico (CC BY-SA 4.0)

  12. How to set the next/image component to 100% height?

    Since 2023, every above solution is deprecated,

    use below

    <Image
      src="url"
      width={0}
      height={0}
      sizes="100vw"
      style={{ width: '100%', height: 'auto' }} // optional
    />
    

    Github: https://github.com/vercel/next.js/discussions/18474#discussioncomment-5501724

    Next.js: https://nextjs.org/docs/app/api-reference/components/image#responsive-images

    From Stack Overflow: asked by Jake, answered by Nisharg Shah (CC BY-SA 4.0)

Related topics

Where these questions come from

Open-source collections on GitHub, official documentation, a government careers service and the Stack Exchange sites, each used under its own licence. The answers are the authors' own words: we only tidy the layout, leave out pictures, and cut a long answer with a link to the rest. Stack Exchange answers stay under CC BY-SA and name who asked and who answered.