Ask questionsBug: useLayoutEffect callback called twice when a dom node is in a dependency array

<!-- Please provide a clear and concise description of what the bug is. Include screenshots if needed. Please test using the latest version of the relevant React packages to make sure your issue has not already been fixed. -->

React version: v16.3.1

Steps To Reproduce

  1. add useLayoutEffect
  2. add dom node to the deps array
  3. invoke setState inside useLayoutEffect callback

<!-- Your bug will get fixed much faster if we can run your code and it doesn't have dependencies other than React. Issues without reproduction steps or code examples may be immediately closed as not actionable. -->

Link to code example:

<!-- Please provide a CodeSandbox (, a link to a repository on GitHub, or provide a minimal code example that reproduces the problem. You may provide a screenshot of the application if you think it is relevant to your bug report. Here are some tips for providing a minimal example: -->

The current behavior

useLayoutEffect callback gets called a second time, although the values in the deps array have not changed

The expected behavior

useLayoutEffect callback should not get called unless values in the dependency array change


Answer questions everdimension


ref.current is undefined initially

Actually, it is defined, AFAU that's the point of useLayoutEffect: by the time it's run, the dom had already been commited. I added an if with an early return to my example to demonstrate that.

You are not supposed to use ref.current as a dependency

I thought that was what official react hooks linter recommended? If that's the wrong way, then what's the proper way to update effect if the dom node changes or gets destroyed?


Related questions

Disable react strict mode on third party libraries hot 6
Refs - &#34;object is not extensible&#34; hot 4
Warning: Unknown DOM property for. Did you mean htmlFor? hot 4
React@16.9 block `javascript:void(0);` hot 4
TypeError: Object(...) is not a function hot 3
Warning: validateDOMNesting(...): <tr> cannot appear as a child of <table> hot 3
React custom hook "Should have a queue. This is likely a bug in React" error message. hot 2
useEffect causes 'callback is not a function' exception hot 2
DevTools: Updating state or props in devtools does not trigger component update. hot 2
Infinite loop in useEffect using blank object or array hot 2
False-positive security precaution warning (`javascript:` URLs) hot 2
Hooks API - hook breaks when exported from module hot 2
Function components do not support contextType. hot 2
Feedback on useEffect depndencies change error hot 2
[ESLint] Feedback for 'exhaustive-deps' lint rule hot 2
Github User Rank List