I am trying to run useEffect only for the first time page load. But it’s running two times when its loading for the first time. I cannot figure it out. Can anyone help me?
Can Some one tell me why this code is running useEffect two times? React 18 I am using.
import axios from "axios";
import React, { useEffect, useState } from "react";
import toast from "react-hot-toast";
import { useParams } from "react-router-dom";
import { BASE_API_URL } from "../Variables/Urls";
const SingleRecipeView = () => {
const { slug } = useParams();
const [recipe, setRecipe] = useState({});
const [loading, setLoading] = useState(true);
const fetchRecipe = async () => {
try {
setLoading(true);
const res = await axios.get(`${BASE_API_URL}/recipe/get/${slug}`);
console.log(res.data);
setRecipe(res.data);
// toast.success("Hurray");
setLoading(false);
} catch (err) {
console.log(err);
setLoading(false);
toast.error("Error loading recipe");
}
};
useEffect(() => {
fetchRecipe();
}, []);
>Solution :
It’s because you are in strict mode.
Please remove StrictMode from the index.js.
//......
root.render(
<StrictMode>
<App />
</StrictMode>
);
to
//......
root.render(<App />);
Please read my answer, if you want to understand this in detailed https://stackoverflow.com/a/61091205/8798220