0

I just created a simple component in ReactJs and call an api with axios but I noticed in browser network tab that my api called twice in first render, also I tested with a console log, it return twice too! why? I googled and people said this is normal in functional component and normal behavior but I don't want request to api twice! any idea?

import React, { useEffect, useState } from "react";

export default function User() {
  useEffect(() => {
    getUser().then(); // it call api twice, I got data twice!
    console.log(111); // return twice
  }, []);

  const getUser = async () => {
    const user = await Api.Get("User");

    if (user.status === 200) {
      console.log(user);
    }
  };

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

Here I use user compontent: Router.js

<BrowserRouter basename="/">
<Routes>
     <Route exact path='/user' element={<User/>}></Route>
</Routes>
</BrowserRouter>
Jack The Baker
  • 1,781
  • 1
  • 20
  • 51

1 Answers1

0

React 18 introduces a new development-only check to Strict Mode. This check automatically unmounts and remounts the component, making the useEffect hook fire twice on the initial mount.

More there:

https://levelup.gitconnected.com/react-18-the-trickiness-of-useeffect-fadfa65fa4b4

Kris1803
  • 82
  • 5