4

I am trying to load data to my App.js file in react from the backend. I have used redux to build the whole data fetching and storing pipeline from backend to frontend. Here is the code :

function App() {
  const dispatch = useDispatch();
  useEffect(() => {
    dispatch(getPosts());
  }, [dispatch]);
  const posts = useSelector((state) => state.posts);
  console.log(posts);
  return (
    <div>
      <h1>App</h1>
    </div>
  );
}

In the above code, the console.log shows the data twice in the google console, whenever the App.js is refreshed. How to make it run only once?

Mario Petrovic
  • 7,500
  • 14
  • 42
  • 62
  • 2
    Are you using react 18 and ``? If so, this is normal. In dev builds, strict mode simulates the component unmounting and remounting. The goal is to make it easier for you to spot bugs caused by forgetting to clean up useEffects – Nicholas Tower Aug 11 '22 at 13:04
  • 1
    If you want to get more detailed explanation regarding `React.StrictMode` and why some callbacks run twice then check this out: [How to Enable React Strict Mode](https://kentcdodds.com/blog/react-strict-mode#:%7E:text=the%20dust%20here.-,It%20runs%20code%20TWICE,-Another%20thing%20that:~:text=the%20dust%20here.-,It%20runs%20code%20TWICE,-Another%20thing%20that) – Botond Balogh Aug 11 '22 at 13:10
  • Does this answer your question? [React 18, useEffect is getting called two times on mount](https://stackoverflow.com/questions/72238175/react-18-useeffect-is-getting-called-two-times-on-mount) – Youssouf Oumar Sep 21 '22 at 15:48

2 Answers2

7

That's because you are running your application in Strict Mode. Go to index.js and comment strict mode tag. You will find a single render.

This happens is an intentional feature of the React.StrictMode. It only happens in development mode and should help to find accidental side effects in the render phase.

This is from the documentation:

Strict mode can’t automatically detect side effects for you, but it can help you spot them by making them a little more deterministic. This is done by intentionally double-invoking the following functions:...

Here you can see the documentation of Strict Mode.

Phillip
  • 170
  • 4
2

It's happening because of StrictMode. It triggers Effects twice to make sure handlers work as intended, It occurs just in development, you will not have same behaviour in a production build, effects will only be called once and when their dependencies change.

If you do not want this behaviour, check for <React.StrictMode> tag and remove it

Evren
  • 4,147
  • 1
  • 9
  • 16