We can use the useRef hook to store any mutable value we like, so we could use that to keep track of if it's the first time the useEffect function is being run.

If we want the effect to run in the same phase that componentDidUpdate does, we can use useLayoutEffect instead.

Example

const { useState, useRef, useLayoutEffect } = React;

function ComponentDidUpdateFunction() {
  const [count, setCount] = useState(0);

  const firstUpdate = useRef(true);
  useLayoutEffect(() => {
    if (firstUpdate.current) {
      firstUpdate.current = false;
      return;
    }

    console.log("componentDidUpdateFunction");
  });

  return (
    <div>
      <p>componentDidUpdateFunction: {count} times</p>
      <button
        onClick={() => {
          setCount(count + 1);
        }}
      >
        Click Me
      </button>
    </div>
  );
}

ReactDOM.render(
  <ComponentDidUpdateFunction />,
  document.getElementById("app")
);
<script src="https://unpkg.com/[email protected]/umd/react.development.js"></script>
<script src="https://unpkg.com/[email protected]/umd/react-dom.development.js"></script>

<div id="app"></div>

Answer from Tholle on Stack Overflow
Top answer
1 of 16
317

We can use the useRef hook to store any mutable value we like, so we could use that to keep track of if it's the first time the useEffect function is being run.

If we want the effect to run in the same phase that componentDidUpdate does, we can use useLayoutEffect instead.

Example

const { useState, useRef, useLayoutEffect } = React;

function ComponentDidUpdateFunction() {
  const [count, setCount] = useState(0);

  const firstUpdate = useRef(true);
  useLayoutEffect(() => {
    if (firstUpdate.current) {
      firstUpdate.current = false;
      return;
    }

    console.log("componentDidUpdateFunction");
  });

  return (
    <div>
      <p>componentDidUpdateFunction: {count} times</p>
      <button
        onClick={() => {
          setCount(count + 1);
        }}
      >
        Click Me
      </button>
    </div>
  );
}

ReactDOM.render(
  <ComponentDidUpdateFunction />,
  document.getElementById("app")
);
<script src="https://unpkg.com/[email protected]/umd/react.development.js"></script>
<script src="https://unpkg.com/[email protected]/umd/react-dom.development.js"></script>

<div id="app"></div>

2 of 16
190

You can turn it into custom hook (new documentation page: Reusing Logic with Custom Hooks), like so:

import React, { useEffect, useRef } from 'react';

const useDidMountEffect = (func, deps) => {
    const didMount = useRef(false);

    useEffect(() => {
        if (didMount.current) func();
        else didMount.current = true;
    }, deps);
}

export default useDidMountEffect;

Usage example:

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

import useDidMountEffect from '../path/to/useDidMountEffect';

const MyComponent = (props) => {    
    const [state, setState] = useState({
        key: false
    });    

    useEffect(() => {
        // you know what is this, don't you?
    }, []);

    useDidMountEffect(() => {
        // react please run me if 'key' changes, but not on initial render
    }, [state.key]);    

    return (
        <div>
             ...
        </div>
    );
}
// ...
🌐
Reddit
reddit.com › r/reactjs › prevent useeffect listening to a state variable to fire on first render
r/reactjs on Reddit: Prevent useEffect listening to a state variable to fire on first render
September 13, 2022 -

Title. Basically i have a useEffect with a specific state variable in the dependency array. I want the side effect to be fired only when it does actually change, not in first render. I tried with a simple useRef guard, but with the new changes to useEffect(fires twice) it doesn't work. Removing the strictmode makes it work, should i just ignore it since when i switch to production it should work?

Discussions

useEffect fires at initial render
When you use useEffect with second parameter different than [], what you expect is it to fire when that variable changes. Not at the initial render. If someone wants something to fire at initial re... More on github.com
🌐 github.com
11
June 12, 2019
reactjs - I want to know why my useEffect function is not running on the first render? - Stack Overflow
I am still learning how first renders work so any help is much appreciated, also if there is any more information needed let me know. ... You are using Ref, which when updates will not trigger a re-render, which means once your REST call returns, the component will not re-render with your new data. Try using state instead of ref. useEffect ... More on stackoverflow.com
🌐 stackoverflow.com
Is there a way to NOT fire a useEffect hook on initial render?
this is what I did to get back componentDidUpdate lifecycle. const loaded = useRef(false); useEffect(() => { if (loaded.current) { if (typeof homework === 'undefined') { informMyParent(); } } else { loaded.current = true; } }, [informMyParent, homework]); It gets a bit annoying. sometimes. More on reddit.com
🌐 r/reactjs
8
1
September 28, 2019
How to make a component render only AFTER a useEffect hook?
The `useEffect` hook runs after render so what you are asking for is not possible. The component will always render twice if you update your state in `useEffect`. You can show a loading state until you either have names successfully or you have encountered an error. As written above, your component has several errors in it. More on reddit.com
🌐 r/reactjs
13
0
January 26, 2023
Top answer
1 of 3
1

Effects don't run during a render.

The first execution of an effect function will be triggered by the first render.

2 of 3
1

useEffect is called after the first render however the issue in your code is that the words state isn't updated when you think it is.

useEffect(() => {
        setWords(sentence.split(' ')); 
// Here you set the words state that will trigger a new render. However the words variable is empty won't be changed until the next render


        words.map(word =>{ //Here you call map on an empty array.
          if(word.length <= 2){
            scrambledWord.push(word);

          }
          else{
            scrambledWord.push(scrambleWord(word));
          }
        })

        setScrambledSentence(scrambledWord.join(' ')); 
        //Here you set the state on an empty string
      }, [])
// the useEffect doesn't run a second time because it has no dependencies.

This code should work:

    const ScrambleSentence = ({sentence}) => {
    const [scrambledSentence, setScrambledSentence] = useState('');


    function scrambleWord(n){
        var text = n.split('');
        for(var i = text.length - 1; i > 0; i--){
            var j = Math.floor(Math.random() * (i + 1));
            var temp = text[i];
            text[i] = text[j];
            text [j] = temp;
        }
        return text.join('');
    }

    useEffect(() => {
        let scrambledWord = [];
        const words = sentence.split(' ')
        words.forEach(word =>{
          if(word.length <= 2){
            scrambledWord.push(word);
          }else{
            scrambledWord.push(scrambleWord(word));
          }
        })

        setScrambledSentence(scrambledWord.join(' '));
      }, [])


      console.log(scrambledSentence);
    return (
        <div>
            <p id='scrambled-word'>{scrambledSentence}</p>
        </div>
    )
};

export default ScrambleSentence;

https://reactjs.org/docs/hooks-state.html

https://reactjs.org/docs/hooks-effect.html

🌐
Medium
dpericich.medium.com › how-to-bypass-useeffect-on-your-first-page-render-c31b7ba112a7
How to Bypass useEffect on Your First Page Render
September 17, 2023 - The useEffect hook can introduce unwanted side effects with initial renders. To bypass this useEffect calls on load, we can use useRef…
🌐
Plain English
plainenglish.io › blog › how-to-make-the-react-useeffect-hook-not-run-on-initial-render
How to Make the React useEffect Hook Not Run on Initial Render?
June 26, 2021 - We can make the React useEffect callback not run on the first render by creating a ref that keeps track of whether the first render is done. Then we can check the ref’s value to see when the first…
🌐
TypeOfNaN
typeofnan.dev › how-to-prevent-useeffect-from-running-on-mount-in-react
How to prevent useEffect from running on mount in React | TypeOfNaN
We probably don’t want to actually ... from the API call. One solution to this problem is employing the useRef hook to track whether the component has mounted or not....
🌐
GitHub
github.com › facebook › react › issues › 15873
useEffect fires at initial render · Issue #15873 · facebook/react
June 12, 2019 - When you use useEffect with second parameter different than [], what you expect is it to fire when that variable changes. Not at the initial render. If someone wants something to fire at initial re...
Author   furkanedu
Find elsewhere
🌐
Medium
medium.com › swlh › prevent-useeffects-callback-firing-during-initial-render-the-armchair-critic-f71bc0e03536
Prevent useEffect’s Callback Firing During Initial Render | by Theviyanthan Krishnamohan | The Startup | Medium
July 7, 2020 - Next, if the current property is false, then that means it is not the initial render and the side effect should be executed. This way we can make sure the callback function is called only when the dependencies change. Now, what if we want to reuse this? Let’s turn this into a custom hook. This hook is syntactically similar to the useEffect hook as it accepts a callback function and an array of dependencies as arguments.
🌐
YouTube
youtube.com › shorts › FAnA6QpSryU
useEffect But It Skips the First Render - YouTube
Handy little custom hook in React #react #reactjs #reactjsdeveloper #programming #progammer #frontend #devtok #coding #code #codetok #cs
Published   August 12, 2024
🌐
DEV Community
dev.to › cassidoo › when-useeffect-runs-3pf3
When useEffect runs - DEV Community
June 4, 2024 - Since useEffect's ===> callback <=== is deferred, it's supposed to run last but it's not a guarantee. While it can't happen before running useEffect (phase 4), it could happen as early as before the browser render (phase 5) depending on how the browser optimizes its work. This is why the useLayoutEffect hook was created, to give us a handle when we need to make sure DOM modifications are applied first (although it has performance implications).
🌐
DhiWise
dhiwise.com › blog › design-converter › simple-ways-to-prevent-useeffect-from-running-on-first-render
Prevent useEffect from Running on First Render in React
February 21, 2025 - In React function components, useEffect helps with tasks like fetching data, updating the DOM, or setting up event listeners. However, sometimes, it runs on the first render when you don’t need it to, which can lead to duplicate API calls or unwanted effects.
🌐
Aakashpatel
aakashpatel.in › how-to-stop-useeffect-from-running-on-the-first-render
How to Stop useEffect From Running on The First Render? | Aakash Patel
May 27, 2025 - Learn how to skip the first render of the useEffect hook in React using a custom hook or useRef to manage the initial render state.
🌐
React
legacy.reactjs.org › docs › hooks-effect.html
Using the Effect Hook – React
We pass a function to the useEffect Hook. This function we pass is our effect. Inside our effect, we set the document title using the document.title browser API. We can read the latest count inside the effect because it’s in the scope of our function. When React renders our component, it will remember the effect we used, and then run our effect after updating the DOM. This happens for every render, including the first one. Experienced JavaScript developers might notice that the function passed to useEffect is going to be different on every render.
🌐
The Web Dev
thewebdev.info › home › how to make the react useeffect hook not run on initial render?
How to Make the React useEffect Hook Not Run on Initial Render? - The Web Dev
March 13, 2021 - When we click on the increment button, we see 'second render' logged after the first render. We can make the React useEffect callback not run on the first render by creating a ref that keeps track of whether the first render is done.
🌐
Reddit
reddit.com › r/reactjs › is there a way to not fire a useeffect hook on initial render?
r/reactjs on Reddit: Is there a way to NOT fire a useEffect hook on initial render?
September 28, 2019 -

This is a bit of a weird question, maybe, but I have a use case for a custom hook based on useEffect to return data from an API based on user input. I have it mostly working however I have noticed that my hook is running on initial render and making an unnecessary API request. Obviously useEffect does this by default, but I was wondering if there was a way to avoid this.

I tried conditionally calling the hook, but React considers that an error and refuses to compile. I also tried conditionally returning within the hook, but same issue. Lastly I tried calling the hook with useCallback, but that still ran on initial render, as well.

My current code is available here: https://codesandbox.io/s/exciting-hooks-1psw6

Any thoughts?

🌐
Greenroots
blog.greenroots.info › react-useeffect-hook-usages-you-must-know
React useEffect Hook usages you must know
March 22, 2022 - You may want to run the side effect just once after the initial render. A typical case will be fetching data making an API call, and storing the response in the state variable after the initial render.
🌐
React
react.dev › reference › react › useEffect
useEffect – React
If your Effect wasn’t caused by an interaction (like a click), React will generally let the browser paint the updated screen first before running your Effect. If your Effect is doing something visual (for example, positioning a tooltip), and the delay is noticeable (for example, it flickers), replace useEffect with useLayoutEffect. If your Effect is caused by an interaction (like a click), React may run your Effect before the browser paints the updated screen. This ensures that the result of the Effect can be observed by the event system. Usually, this works as expected.
🌐
Reddit
reddit.com › r/reactjs › how to make a component render only after a useeffect hook?
r/reactjs on Reddit: How to make a component render only AFTER a useEffect hook?
January 26, 2023 -

I have a component with a useEffect to fetch some data and it conditionally renders different children based on the response. So something like this

function Component() {
    const [names, setNames] = useState([])

    useEffect(() => {
        getNames().then(data => names = data)
    }, [names])

    return (
        <div>
            {names.length ? <Success /> <Error />}
        </div>
    )

Upon first render, it shows the Error component, and right after a split second, it shows the Success component. I want it to only render once the useEffect is finished. Is there anyway to do that?

🌐
JavaScript in Plain English
javascript.plainenglish.io › how-to-make-the-react-useeffect-hook-not-run-on-initial-render-aca1ac7a7ac2
How to Make the React useEffect Hook Not Run on Initial Render? | by John Au-Yeung | JavaScript in Plain English
June 27, 2021 - import React, { useEffect, useRef, useState } from "react";const useDidMountEffect = (func, deps) => { const didMount = useRef(false); useEffect(() => { if (didMount.current) { func(); } else { didMount.current = true; } }, deps); };export default function App() { const [count, setCount] = useState(0); useDidMountEffect(() => { console.log("second render"); }); return ( <div className="App"> <button onClick={() => setCount((c) => c + 1)}>increment</button> <p>{count}</p> </div> ); } We create the useDidMountEffect hook to track whether the first render is done.