Does a render happen before function in React Hooks useEffect is called?

Effects created using useEffect are run after the render commit phase and hence after the render cycle. This is to make sure that no side-effects are executed during the render commit phase which might cause inconsistency

According to the documentation

Mutations, subscriptions, timers, logging, and other side effects are
not allowed inside the main body of a function component (referred to
as React’s render phase). Doing so will lead to confusing bugs and
inconsistencies in the UI.

The function passed to useEffect will run
after the render is committed to the screen.

useEffect hook can be used to replicate behavior of componentDidMount, componentDidUpdate, and componentWillUnmount lifecycle methods for class components depending the arguments passed to the dependency array which is the second argument to useEffect and the return function from within the callback which is executed before the next effect is run or before unmount

For certain useCases such as animations you may make use of useLayoutEffect which is executed synchronously after all DOM mutations. Use this to read layout from the DOM and synchronously re-render. Updates scheduled inside useLayoutEffect will be flushed synchronously, before the browser has a chance to paint.

Leave a Comment