React Hooks - useEffect fires even though the state did not change
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: [...]
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.