What is React useEffect?
About
- is asynchronous
- and executes at the end of the rendering.
Specifically, it runs at the end of a commit after the screen updates, after every render
- When you want to do something with the DOM node (outside rendering)
- The DOM element does not exist yet (not yet rendered)
- To synchronize with an external system (editor)
In React, rendering should be a pure calculation of JSX and should not contain side effects like modifying the DOM.
Don't useState as it will trigger a new render, that will trigger useEffect again
You can tell React:
- to skip unnecessarily re-running the Effect by specifying an array of dependencies as the second argument,
- even an empty array to run once.
Support
Warning: Cannot update a component () while rendering a different component ().
Typically, if you get this message, you need to encapsulate your state in a useEffect function
Warning: Cannot update a component (`xxxxx`) while rendering a different component (`xxxxxx`).
To locate the bad setState() call inside `xxxx`, follow the stack trace as described in https://reactjs.org/link/setstate-in-render