Search code examples
reactjsreact-hooksuse-effectuse-statererender

Why does a function outside useEffect get called while a function inside useEffect without dependency array doesn't?


Until today I thought that code inside an useEffect without dependency array and code outside useEffect both trigger on every rerender, but then I found this weird case and I don't understand why is this happening.

In THIS example, the first time you click the button it triggers a setState to a different value so it rerenders and both console.log are called, but the second time you click the button a setState is called with the same value, still the outside console.log gets called, but the console.log inside useEffect doesn't... why? Is this not a full rerender? How can the component get reevaluated without triggering useEffect again?

The next time you click the button nothing happens because calling setState with the same value doesnt trigger a rerender, but the first time does that weird half-rerender thing that I dont understand.

Thanks in advance.


Solution

  • I will answer my question:

    This behavior is actually explained in the official docs and nothing to worry about since it's not a "real" render.

    This is the relevant part:

    If you update a State Hook to the same value as the current state, React will bail out without rendering the children or firing effects. [...]

    So basically React evaluates the function, so the outside console.log will be called but then it just bails out without rerendering the children or firing useEffect