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 does this React's useEffect() fires twice after loaded?

I have this very simple component called Editor:

export default function Editor() {
  const [error, setError] = useState(null);
  const [isLoaded, setIsLoaded] = useState(false);
  const [currentData, setCurrentData] = useState({});

  useEffect(() => {
    fetch("http://localhost:4000/pages")
      .then(res => res.json())
      .then(
        (result) => {
          setIsLoaded(true);
          setCurrentData(result);
        },
        (error) => {
          setIsLoaded(true);
          setError(error);
        }
      )
  }, [])

  if (error) {
    return (
      <LoadingError value={error.message} />
    );
  } else if (!isLoaded) {
    return (
      <Loading />
    )
  } else {
    console.log(currentData);
  }

  return ( <div></div> );
}

Notice the last else condition, where my currentData is logged into the console.

What happens when this component is rendered is that my console.log() fires twice! The first time my currentData object is empty. The second time, the object properly contains all the data from my API.

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

However, as my console.log() should fire only when there is no error (the first if condition), and only when the data is loaded (the second else if condition), how is it possible that I end up with empty object in the console the first time? What am I doing wrong?

>Solution :

Why does this React’s useEffect() fires twice after loaded?

It doesn’t.

The function Editor runs again because you call setIsLoaded and setCurrentData once the promise in the effect (which runs only once) resolves.

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