skip to Main Content

I have been trying to migrate a React.js CRA to Next.js SSR Application, I moved specifically to Next.js 11 as I have some package deps which support only up Next.js 11, as my CRA application is working perfect, but when I moved all my project files to Next.js 11, all my API calls are triggering 2 times when I visit the page, I’m using react 16 and axios to fetch data from my backend, please help me to fix this issue :

Here is sample code :

in pages/test/index.js

"use client"

import React from 'react';
import Test from '../../src/components/test';

const Asdf = () => {
    return ( 
        <Test />
     );
}
 
export default Asdf;

here is the component :

"use client"

import Axios from 'axios';
import React, { useEffect, useState } from 'react';

const Test = () => {

    const [data, setData] = useState([])

    useEffect(() => {
        Axios.get('https://dummyjson.com/products/')
        .then(res => setData(res))
    }, [])

    return ( 
        <>
           test page
        </>
     );
}

export default Test;

In network tab, you can notice 4 request, 2 are preflight and rest 2 calls being triggered :

enter image description here

Is there anyways to prevent it or what I’m doing wrong, please let me know! Thanks in advance.

2

Answers


  1. You can add reactStrictMode: false in next.config.js

    const nextConfig = {
      reactStrictMode: false,
    };
    

    Once added don’t forget to restart the project

    Here you have more info!

    https://nextjs.org/docs/pages/api-reference/next-config-js/reactStrictMode

    Login or Signup to reply.
  2. If you’re using React 18 or above, it’s because React introduces strict mode. It’s basically a feature to help you find bugs in the development environment and won’t influence the production environment. Here is the note from React’s documentation:

    Strict Mode enables the following checks in development:

    • Your components will re-render an extra time to find bugs caused by impure rendering.
    • Your components will re-run Effects an extra time to find bugs caused by missing Effect cleanup.
    • Your components will be checked for usage of deprecated APIs.
    • All of these checks are development-only and do not impact the production build.

    If you want to avoid this behavior, just go to the next.config file and change the reactStrictMode to false:

    const nextConfig = {
      reactStrictMode: false,
    };
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search