0

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

Youssouf Oumar
  • 29,373
  • 11
  • 46
  • 65
  • For best performance use useCallback hook on your fetchRecipe function and include it in useEffect dependancy array. One more thing you can do is to do the request directly in the useEffect which is maybe the cleanest way of what you want to do – Dario K Jul 09 '22 at 18:14

1 Answers1

4

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

Nisharg Shah
  • 16,638
  • 10
  • 62
  • 73
  • Thank you brother. I didn't know about this that I had to remove strict mode. In previous version it wasn't like that. This is new in react 18? – Debanjan Tewary Jul 09 '22 at 18:28
  • No, it already exists on the lower versions of the react. – Nisharg Shah Jul 09 '22 at 18:42
  • Removing Strict Mode is not always a good thing. It's there for a good reason. See [what's StrictMode in React?](https://stackoverflow.com/questions/53183362/what-is-strictmode-in-react) – Youssouf Oumar Jul 09 '22 at 18:45
  • Also, while `StrictMode` existed before, the behaviour you have @DebanjanTewary is introduced by React 18. You can read about it [here](https://stackoverflow.com/questions/72238175/react-18-useeffect-is-getting-called-two-times-on-mount). – Youssouf Oumar Jul 09 '22 at 18:49