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 :
Is there anyways to prevent it or what I’m doing wrong, please let me know! Thanks in advance.
2
Answers
You can add reactStrictMode: false in next.config.js
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
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:
If you want to avoid this behavior, just go to the next.config file and change the
reactStrictMode
to false: