Middle+
What will be displayed in the console during the first render of a React component with a child component (useLayoutEffect, useEffect)?
sobes.tech AI
Answer from AI
On the initial render of a React component with a child component that uses the hooks useLayoutEffect and useEffect, the call order will be as follows:
- React first renders the DOM.
- Then, the callback from useLayoutEffect is executed — it is called synchronously immediately after the DOM changes, but before the browser repaints.
- After that, the browser updates the screen.
- Only then, the callback from useEffect is executed — it is called asynchronously after the browser has painted the changes.
Example console output:
function Child() {
React.useLayoutEffect(() => {
console.log('useLayoutEffect');
}, []);
React.useEffect(() => {
console.log('useEffect');
}, []);
return <div>Child</div>;
}
function Parent() {
return <Child />;
}
// On the first render, the console will show:
// useLayoutEffect
// useEffect
Thus, useLayoutEffect fires before useEffect during the initial render.