49

I have set up an effect inside my component, which changes the view if another state attribute changes. But for some reason, when the component mounts, the effect is run, even though the value of detailIndex has not changed.

const EventsSearchList = () => { const [view, setView] = useState('table'); const [detailIndex, setDetailIndex] = useState(null); useEffect(() => { console.log('onMount', detailIndex); // On mount shows "null" }, []); useEffect( a => { console.log('Running effect', detailIndex); // On mount shows "null"!! Should not have run... setView('detail'); }, [detailIndex] ); return <div>123</div>; }; 

Why is this happening?

UPDATE: In case it is not clear, what I am trying is to run the effect when the component updates because detailIndex changes. NOT when it mounts.

10
  • 2
    useEffects always fires on mount AFAIK. Commented Feb 28, 2019 at 10:52
  • 2
    It was my understanding that this only happens if the second parameters is [] Commented Feb 28, 2019 at 10:52
  • That's used for when re-rendering the component I think. What are you trying to accomplish? Commented Feb 28, 2019 at 10:53
  • 1
    @EnriqueMorenoTent no, the second parameter defines when to rerun this effect, and [detailIndex] means it will rerun every time detailIndex changes ([] means there is no rerun). Commented Feb 28, 2019 at 10:53
  • 1
    Just a stupid guess but have you tried useState(undefined) instead on useState(null). My dumb first thought is that, your state was previously undefined and you just set it to null, so useEffect is triggered. But it is more likely that useEffect is always executed on mount even though you passed a dependecy value. Commented Feb 28, 2019 at 10:56

6 Answers 6

30

useEffect from React Hooks is by default executed on every render, but you can use second parameter in function to define when the effect will be executed again. That means that function is always executed on mount. In your situation your second useEffect will be run on start and when detailIndex changes.

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

Source:

Experienced JavaScript developers might notice that the function passed to useEffect is going to be different on every render. [...] You can tell React to skip applying an effect if certain values haven’t changed between re-renders. To do so, pass an array as an optional second argument to useEffect: [...]

Sign up to request clarification or add additional context in comments.

3 Comments

It's also worth noting that the function in useEffect is run after the render, rather than before. Very easy to forget as these definitions are usually at the top of the function component definitions.
can anyone please explain to me what this statement means from the docs? Experienced JavaScript developers might notice that the function passed to useEffect is going to be different on every render. We pass an arrow function to useEffect and it is called everytime after render, from the closure the state and prop values might be different to what it has, but how come the function itself is different?
@ChaitanyaTetali Declaration of function happens at every render, but useEffect calls the function according to dependency array. The state values might be different only when component didn't rerender yet. It might happen eg. when there are multiple state changes in single mouse click handler.
29

In my case, the component kept updating even though I used the second argument in useEffect() and I was printing the argument to make sure it did not change and it did not change. The problem was that I was rendering the component with map() and there were cases where the key changed, and if the key changes, for react, it is a completely different object.

1 Comment

This answer was extremely useful!
9

One way to make sure code in useEffect only runs when a dependency has changed, and not on initial mount (first render), is to assign a variable that is initially false and only becomes true after the first render, and this variable naturally should be a hook, so it will be memo-ed across the component's lifespan.

Comparison of 3 different useEffect:

const {useEffect, useRef, useState} = React const App = () => { const mountedRef = useRef() // ← the "flag" const [value, setValue] = useState(false) // simulate a state change // with the trick useEffect(() => { if (mountedRef.current){ // ← the trick console.log("trick: changed") } }, [value]) // without the trick useEffect(() => { console.log("regular: changed") }, [value]) // fires once & sets "mountedRef" ref to "true" useEffect(() => { console.log("rendered") mountedRef.current = true // update the state after some time setTimeout(setValue, 1000, true) }, []) return null } ReactDOM.createRoot(document.getElementById('root')).render(<App/>)
<script crossorigin src="https://unpkg.com/react@18/umd/react.development.js"></script> <script crossorigin src="https://unpkg.com/react-dom@18/umd/react-dom.development.js"></script> <div id="root"></div>

Comments

6

You can add a second guard, check if detailIndex has changed from the initial value says -1

 useEffect( a => { if(detailIndex != -1) { console.log('Running effect', detailIndex); // On mount shows "null"!! Should not have run... setView('detail'); }}, [detailIndex]); 

2 Comments

Is a guard the only way to do this? It seems so hacky for a framework like React
@FabricioG We can use useRef() instead, checkout this excellent explanation in stackoverflow: stackoverflow.com/questions/55075604/…
3

If and only if the useEffect's second parameter state changes by reference (not value), the effect fires.

import React, { useState, useEffect } from 'react'; function App() { const [x, setX] = useState({ a: 1 }); useEffect(() => { console.log('x'); }, [x]); setInterval(() => setX({ a: 1 }), 1000); return <div></div> } } export default App; 

In this code snippet, the log is printed in every second, because, every time setX({a: 1}) is called, x state is updated with a new reference to a new object.

If setX({a: 1}) was replaced by setX(1), effect would not fire periodically.

Comments

3

useEffect is always ran after the initial render.

From docs:

Does useEffect run after every render? Yes! By default, it runs both after the first render and after every update. (We will later talk about how to customize this.) Instead of thinking in terms of “mounting” and “updating”, you might find it easier to think that effects happen “after render”. React guarantees the DOM has been updated by the time it runs the effects.

Regarding your code, the following will only run once since no dependencies are specified (useEffect takes an optional array of dependencies as a second argument):

useEffect(() => { console.log('onMount', detailIndex); // On mount shows "null" -> since default value for detailIndex is null as seen above // const [detailIndex, setDetailIndex] = useState(null); }, []); 

And this effect will trigger both after the initial render and when the detailIndex changes (try calling setDetailIndex within the previous useEffect):

useEffect(() => // ... effect code }, [detailIndex]); 

useEffect hook API reference

2 Comments

Hi Pavel, I think your answer contradicts itself. You first say that useEffect is always triggered by the initial render (it is), then you say in your final example that it will run only when detailIndex changes. This is not true, as it will also run after the initial render.
Hey @liquidki, I didn't mean it this way - I guess my wording could've been more clear. What you are saying is correct - the effect in the final example will run both after the initial render and every time the detailIndex changes. Thanks for pointing this out - I've corrected my answer.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.