718

I am writing code so that before the data is loaded from DB, it will show loading message, and then after it is loaded, render components with the loaded data. To do this, I am using both useState hook and useEffect hook. Here is the code:

The problem is, useEffect is triggered twice when I check with console.log. The code is thus querying the same data twice, which should be avoided.

Below is the code that I wrote:

import React from 'react';
import './App.css';
import {useState,useEffect} from 'react';
import Postspreview from '../components/Postspreview'

const indexarray=[]; //The array to which the fetched data will be pushed

function Home() {
   const [isLoading,setLoad]=useState(true);
   useEffect(()=>{
      /*
      Query logic to query from DB and push to indexarray
      */
          setLoad(false);  // To indicate that the loading is complete
    })
   },[]);
   if (isLoading===true){
       console.log("Loading");
       return <div>This is loading...</div>
   }
   else {
       console.log("Loaded!"); //This is actually logged twice.
       return (
          <div>
             <div className="posts_preview_columns">
             {indexarray.map(indexarray=>
             <Postspreview
                username={indexarray.username}
                idThumbnail={indexarray.profile_thumbnail}
                nickname={indexarray.nickname}
                postThumbnail={indexarray.photolink}
             />
             )}
            </div>
         </div>  
         );
    }
}

export default Home;

Why it is called twice, and how to fix the code properly?

5
  • 4
    you say when you check the console.log but there is no console.log
    – Joe Lloyd
    Commented Mar 10, 2020 at 13:45
  • 4
    Deleted them initially because I pretty much explained what happened, but added them back for clarity as per your comment.
    – J.Ko
    Commented Mar 10, 2020 at 13:52
  • My Solution is stackoverflow.com/a/72676006/2184182 shared here. I guess help to you. Commented Jun 19, 2022 at 10:21
  • 3
    For those are using React 18 stackoverflow.com/questions/72238175/…. Commented Sep 21, 2022 at 14:28
  • 4
    I am sure this is happening because of <React.Strict>. try replacing <React.Strict><Home></React.Strict> with only <Home>. strict mode renders component twice on local and once on production. Commented Aug 3, 2023 at 2:59

24 Answers 24

1153

Put the console.log inside the useEffect

Probably you have other side effects that cause the component to rerender but the useEffect itself will only be called once. You can see this for sure with the following code.

useEffect(()=>{
      /*
      Query logic
      */
      console.log('i fire once');
},[]);

If the log "i fire once" is triggered more than once it means your issue is one of 3 things.

This component appears more than once in your page

This one should be obvious, your component is in the page a couple of times and each one will mount and run the useEffect

Something higher up the tree is unmounting and remounting

The component is being forced to unmount and remount on its initial render. This could be something like a "key" change happening higher up the tree. you need to go up each level with this useEffect until it renders only once. then you should be able to find the cause or the remount.

React.Strict mode is on

StrictMode renders components twice (on dev but not production) in order to detect any problems with your code and warn you about them (which can be quite useful).

This answer was pointed out by @johnhendirx and written by @rangfu, see link and give him some love if this was your problem. If you're having issues because of this it usually means you're not using useEffect for its intended purpose. There's some great information about this in the docs you can read that here

8
  • 3
    But it is not specified anywhere that StrictMode cause useEffect to run twice too. Strict Mode is used to detect if we are doing side effect in any function which should be pure so only those functions that needed to be pure are run twice but as useEffect can contain side effects it should be run twice in Strict Mode. Any documentation around this stating that useEffect is also run twice?
    – Suraj Jain
    Commented Aug 4, 2022 at 3:56
  • For a more detailed answer about Strict Mode stackoverflow.com/questions/72238175/…. Commented Sep 21, 2022 at 19:00
  • 73
    Man, strict mode should issue a warning that it does this in dev environments. I really wish it wouldn't do that silently Commented Oct 29, 2022 at 12:25
  • 1
    For those who are using NextJS, check on your next.config.js: [module.exports = { reactStrictMode: true, <== False to disable strict mode }]
    – slumbering
    Commented Mar 31, 2023 at 9:57
  • 2
    @slumbering you should not disable this, you should change your code to work better in strict mode.
    – Joe Lloyd
    Commented Mar 31, 2023 at 11:03
347

Remove <React.StrictMode> from index.js This code will be

root.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>
);

this

root.render(
    <App />
);

React StrictMode renders components twice on dev server

8
  • 4
    Oh man, StrictMode was the culprit. Yeasin it would be great if you could give more explaination about it too
    – Yash Pokar
    Commented Aug 29, 2022 at 7:45
  • 9
    @YashPokar According to my understanding , React StrictMode renders the components twice as mentioned. Why? To identify components with unsafe life cycle as you can see here -> reactjs.org/docs/strict-mode.html#identifying-unsafe-lifecycles . In other words to make sure the components are resilient to mounting and unmounting The best solution would be writing the cleanup function if you are using useEffect. If you really have some heavy stuffs in useEffect , maybe move those out from useEffect all together.
    – Sandy B
    Commented Sep 3, 2022 at 7:37
  • 6
    Removing StrictMode is the last thing to do. It's there for a purpose. See stackoverflow.com/questions/72238175/…. Commented Sep 21, 2022 at 19:01
  • 1
    I was going to say that @YoussoufOumar , StrictMode shouldn't be tampered with. Thanks for pointing that out. Commented Jul 30, 2023 at 21:30
  • So... what is the solution then? StrictMode causes a bug which is a huge problem.
    – Kokodoko
    Commented Mar 23 at 16:40
67

You are most likely checking the issue on a dev environment with strict mode enabled. To validate this is the case, search for <React.StrictMode> tag and remove it, or build for production. The double render issue should be gone. From React official 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:

  • Functions passed to useState, useMemo, or useReducer
  • [...]

Strict Mode - Reactjs docs

Similar question here My React Component is rendering twice because of Strict Mode

2
  • But useEffect is not on the list of hooks that get double-invoked. In fact, useEffect isn't mentioned in the documentation of Strict Mode. In my app it seems like double invoking happens in some cases and not others.
    – Qwertie
    Commented Apr 30, 2022 at 2:35
  • 1
    I didn't check if useEffect is mentioned in the docs, but it lives inside the render function, so the comments should apply to it too.
    – marcelocra
    Commented Jun 20, 2022 at 0:58
57

As others have already pointed out, this happens most likely due to a Strict Mode feature introduced in React 18.0.

I wrote a blog post that explains why this is happening and what you can do to work around it.

But if you just want to see the code, here you go:

const initialized = useRef(false)

useEffect(() => {
  if (!initialized.current) {
    initialized.current = true

    // My actual effect logic...
    ...
  }
}, [])

Or as a re-usable hook:

import type { EffectCallback } from "react"
import { useEffect, useRef } from "react"

export function useOnMountUnsafe(effect: EffectCallback) {
  const initialized = useRef(false)

  useEffect(() => {
    if (!initialized.current) {
      initialized.current = true
      effect()
    }
  }, [])
}

Please keep in mind that you should only resort to this solution if you absolutely have to!

3
  • Seconding / underscoring that this should be a fallback solution to debug — not a 'solution'. Commented Jun 18, 2023 at 13:11
  • 2
    Why use it as last resort? .. Is there something wrong using the useRef as a sentinel flag?
    – Chen A.
    Commented Oct 5, 2023 at 21:58
  • This doesn't work because Strictmode only runs in development environments (i.e. npm start). When you build (npm run build), then strictmode doesn't run anymore, the useEffect with an empty dep list will only run once not twice.
    – goamn
    Commented Mar 4 at 22:41
28

Please check your index.js

  <React.StrictMode>
    <App />
  </React.StrictMode>

Remove the <React.StrictMode> wrapper you should now fire once

root.render(
    <App />
);
1
28

if you are using Next js, change reactStrictMode from "true" to false :

add this to your next.config.js

reactStrictMode: false,
3
25

react root > index.js > remove <React.StrictMode> wrapper

2
  • 8
    As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.
    – Community Bot
    Commented Sep 12, 2022 at 23:28
  • 2
    This worked for me. I'm just gonna up vote it up.
    – TonyCruze
    Commented Jan 3, 2023 at 22:38
20

It is the feature of ReactJS while we use React.StrictMode. StrictMode activates additional checks and warnings for its descendants nodes. Because app should not crash in case of any bad practice in code. We can say StrictMode is a safety check to verify the component twice to detect an error.

You will get this <React.StricyMode> at root of the component.

root.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>
);

if you want to restrict components to render twice, You can remove <React.StrictMode> and check it. But It is necessary to use StrictMode to detect a run time error in case of bad code practice.

14

React strict mode renders components twice on the dev server.

So, you have to remove StrictMode from index.js. Your index.js current code can be below.

root.render(
 <React.StrictMode>
 <App />
 </React.StrictMode>
);

After removing StrictMode it should look like below

root.render(
 <App />
);
10

I have found a very good explanation behind twice component mounting in React 18. UseEffect called twice in React

Note: In production, it works fine. Under strict mode in the development environment, twice mounting is intentionally added to handle the errors and required cleanups.

8

The new React docs (currently in beta) have a section describing precisely this behavior:

How to handle the Effect firing twice in development

From the docs:

Usually, the answer is to implement the cleanup function. The cleanup function should stop or undo whatever the Effect was doing. The rule of thumb is that the user shouldn’t be able to distinguish between the Effect running once (as in production) and a setup → cleanup → setup sequence (as you’d see in development).

So this warning should make you double check your useEffect, usually means you need to implement a cleanup function.

5

I'm using this as my alternative useFocusEffect. I used nested react navigation stacks like tabs and drawers and refactoring using useEffect doesn't work on me as expected.

import React, { useEffect, useState } from 'react'
import { useFocusEffect } from '@react-navigation/native'

const app = () = {

  const [isloaded, setLoaded] = useState(false)


  useFocusEffect(() => {
      if (!isloaded) {
        console.log('This should called once')

        setLoaded(true)
      }
    return () => {}
  }, [])

}

Also, there's an instance that you navigating twice on the screen.

0
4

It is strict mode in my case. Remove strict mode component at index.tsx or index.jsx

1
  • 1
    As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.
    – Community Bot
    Commented Sep 4, 2022 at 16:15
4

This may not be the ideal solution. But I used a workaround.

var ranonce = false;
useEffect(() => {
    if (!ranonce) {

        //Run you code

        ranonce = true
    }
}, [])

Even though useEffect runs twice code that matters only run once.

4

I found a rather useful solution which is 100% react.

In my case I have a token which I'm using to make a POST request which logs out my current user.

I'm using a reducer with state like this:

export const INITIAL_STATE = {
  token: null
}

export const logoutReducer = (state, action) => {

  switch (action.type) {

    case ACTION_SET_TOKEN :

      state = {
        ...state,
        [action.name] : action.value
      };

      return state;

    default:
      throw new Error(`Invalid action: ${action}`);
  }

}

export const ACTION_SET_TOKEN = 0x1;

Then in my component I'm checking the state like this:

import {useEffect, useReducer} from 'react';
import {INITIAL_STATE, ACTION_SET_TOKEN, logoutReducer} from "../reducers/logoutReducer";

const Logout = () => {

  const router = useRouter();
  const [state, dispatch] = useReducer(logoutReducer, INITIAL_STATE);

  useEffect(() => {

    if (!state.token) {
    
      let token = 'x' // .... get your token here, i'm using some event to get my token

      dispatch(
        {
          type : ACTION_SET_TOKEN,
          name : 'token',
          value : token
        }
      );
    
    } else {
    
      // make your POST request here
      
    }
    
 }

The design is actually nice - you have the opportunity to discard your token from storage after the POST request, make sure the POST succeeds before anything. For async stuff you can use the form :

  POST().then(async() => {}).catch(async() => {}).finally(async() => {})

all running inside useEffect - works 100% and within I think what the REACT developers had in mind - this pointed out that I actually had more cleanup to do (like removing my tokens from storage etc) before everything was working but now I can navigate to and from my logout page without anything weird happening.

3

If someone comes here using NextJS 13, in order to remove the Strict mode you need to add the following on the next.config.js file:

const nextConfig = {
  reactStrictMode: false
}
module.exports = nextConfig

When I created the project it used "Strict mode" by default that's why I must set it explicitly.

2
  • 1
    Cool, but what is the downside of not running the app in "strict mode"?
    – cy23
    Commented May 31, 2023 at 15:11
  • 1
    The "strict mode" prevent you from possible issues giving you some warnings. You can check more about it here: react.dev/reference/react/StrictMode Commented Jun 1, 2023 at 9:43
2

Not sure why you won't put the result in state, here is an example that calls the effect once so you must have done something in code not posted that makes it render again:

const App = () => {
  const [isLoading, setLoad] = React.useState(true)
  const [data, setData] = React.useState([])
  React.useEffect(() => {
    console.log('in effect')
    fetch('https://jsonplaceholder.typicode.com/todos')
      .then(result => result.json())
      .then(data => {
        setLoad(false)//causes re render
        setData(data)//causes re render
      })
  },[])
  //first log in console, effect happens after render
  console.log('rendering:', data.length, isLoading)
  return <pre>{JSON.stringify(data, undefined, 2)}</pre>
}

//render app
ReactDOM.render(<App />, document.getElementById('root'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
<div id="root"></div>

To prevent the extra render you can combine data and loading in one state:

const useIsMounted = () => {
  const isMounted = React.useRef(false);
  React.useEffect(() => {
    isMounted.current = true;
    return () => isMounted.current = false;
  }, []);
  return isMounted;
};


const App = () => {
  const [result, setResult] = React.useState({
    loading: true,
    data: []
  })
  const isMounted = useIsMounted();
  React.useEffect(() => {
    console.log('in effect')
    fetch('https://jsonplaceholder.typicode.com/todos')
      .then(result => result.json())
      .then(data => {
        //before setting state in async function you should
        //  alsways check if the component is still mounted or
        //  react will spit out warnings
        isMounted.current && setResult({ loading: false, data })
      })
  },[isMounted])
  console.log(
    'rendering:',
    result.data.length,
    result.loading
  )
  return (
    <pre>{JSON.stringify(result.data, undefined, 2)}</pre>
  )
}

//render app
ReactDOM.render(<App />, document.getElementById('root'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
<div id="root"></div>

10
  • 4
    For someone that is having issues with having mutiple undesire runs of the useEffect hook I DONT recommend adding extra complexity by using a custom hook like that (useIsMounted).He should understand why is that happening and fix it accordingly. Commented Mar 10, 2020 at 14:11
  • @LuisGurmendez Recommending checking if the component is still mounted before setting state with asynchronous result is sound advice. If op has unexpected calls to the effect then the code posted in the question does not demonstrate that.
    – HMR
    Commented Mar 10, 2020 at 15:10
  • If that’s the case he can use the return funcion of the useEffect callback to make appropiate cleanups Commented Mar 10, 2020 at 15:12
  • @LuisGurmendez Class method isMounted has nothing to do with custom hook called useIsMounted I could have called that hook anything as long as it starts with use. They are completely different things.
    – HMR
    Commented Mar 10, 2020 at 15:17
2

As mentioned, StrictMode is there for a purpose, and it may not always be correct to just disable strictMode to get rid of the issue.

useEffect's callback should ideally return a cleanup function, which gets called before executing the useEffect next time. With respect to the posted question, We can easily clean the array in the cleanup task, so that the array does not contain duplicate data.

 useEffect(()=>{
      // Fill the array here.
      
      // Return a cleanup callback
      return () => {
          // At this point, We can clean the array.
      } 
    
 },[]);

Providing a more concrete example from a coding project, where i am raising a setInterval call and registering for some notitification.

 useEffect(() => {
    let notificationId = StoreManager.registerForUpdateNotification(() => {
      setStore(StoreManager.getInstance());
    });
    let syncIntervalId = setInterval(() => {
      StoreManager.syncStoreWithCloudInstance();
    }, 1 * 30 * 1000);


    return () => {
      StoreManager.deregisterForUpdateNotification(notificationId);
      clearInterval(syncIntervalId);
    }
  }, []);
1

I've had this issue where something like:

const [onChainNFTs, setOnChainNFTs] = useState([]);

would trigger this useEffect twice:

useEffect(() => {
    console.log('do something as initial state of onChainNFTs changed'); // triggered 2 times
}, [onChainNFTs]);

I confirmed that the component MOUNTED ONLY ONCE and setOnChainNFTs was NOT called more than once - so this was not the issue.

I fixed it by converting the initial state of onChainNFTs to null and doing a null check.

e.g.

const [onChainNFTs, setOnChainNFTs] = useState(null);
useEffect(() => {
if (onChainNFTs !== null) {
    console.log('do something as initial state of onChainNFTs changed'); // triggered 1 time!
}
}, [onChainNFTs]);
1

Here is the custom hook for your purpose. It might help in your case.

import {
  useRef,
  EffectCallback,
  DependencyList,
  useEffect
} from 'react';

/**
 * 
 * @param effect 
 * @param dependencies
 * @description Hook to prevent running the useEffect on the first render
 *  
 */
export default function useNoInitialEffect(
  effect: EffectCallback,
  dependancies?: DependencyList
) {
  //Preserving the true by default as initial render cycle
  const initialRender = useRef(true);

  useEffect(() => {
   
    let effectReturns: void | (() => void) = () => {};
    
    /**
     * Updating the ref to false on the first render, causing
     * subsequent render to execute the effect
     * 
     */
    if (initialRender.current) {
      initialRender.current = false;
    } else {
      effectReturns = effect();
    }

    /**
     * Preserving and allowing the Destructor returned by the effect
     * to execute on component unmount and perform cleanup if
     * required.
     * 
     */
    if (effectReturns && typeof effectReturns === 'function') {
      return effectReturns;
    } 
    return undefined;
  }, dependancies);
}

0

Updated

Given that the issue has been previously identified within this thread, it is imperative to provide an update on the details regarding StrictMode. , StrictMode also offers the flexibility of partial utilization, enabling developers to apply it selectively to certain components, thereby enhancing the development process.

import { StrictMode } from 'react';

function App() {
  return (
    <>
      <Header />
      <StrictMode>
        <main>
          <Sidebar />
          <Content />
        </main>
      </StrictMode>
      <Footer />
    </>
  );
}

In this example, Strict Mode checks will not run against the Header and Footer components. However, they will run on Sidebar and Content, as well as all of the components inside them, no matter how deep.

-1

When you are running React in development mode. It will sometimes run twice. Test it in prod environment and your useEffect will only run once.

1
  • 2
    As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.
    – Community Bot
    Commented Jul 19, 2022 at 15:46
-2

in my case just i change useEffect(()=>{ //.... }) to useEffect(()=>{ //.... },[])

-5

I used CodeSandbox and removing prevented the issue.

CodeSandbox_sample

Not the answer you're looking for? Browse other questions tagged or ask your own question.