Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why useEffect running two times?

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();
  }, []);

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading