Skip to content
Onsite

Predict render, layout effect, effect and cleanup log order for a parent and child on mount and update.

MediumP2Output

A Parent component renders a Child. Each has one layout effect and one passive effect with a cleanup, and no dependency arrays:

function Parent() {
  console.log('Parent render');
  useLayoutEffect(() => { console.log('Parent layout'); return () => console.log('Parent layout cleanup'); });
  useEffect(() => { console.log('Parent effect'); return () => console.log('Parent effect cleanup'); });
  return <Child />;
}
// Child is the same with 'Child' in the messages.

The snippet models React's order for the first mount and for one update, using the order React 18 and 19 follow in the browser. What does it print?

1const parent = { name: 'Parent', cleanups: {} };
2const child = { name: 'Child', cleanups: {} };
3const topDown = [parent, child];
4const bottomUp = [child, parent];
5
6function runEffect(c, kind) {
7 console.log(c.name + ' ' + kind);
8 c.cleanups[kind] = () => console.log(c.name + ' ' + kind + ' cleanup');
9}
10
11function commit() {
12 topDown.forEach((c) => console.log(c.name + ' render'));
13 bottomUp.forEach((c) => c.cleanups.layout?.());
14 bottomUp.forEach((c) => runEffect(c, 'layout'));
15 bottomUp.forEach((c) => c.cleanups.effect?.());
16 bottomUp.forEach((c) => runEffect(c, 'effect'));
17}
18
19console.log('mount');
20commit();
21console.log('update');
22commit();
Saved automatically

One line per console.log. Arrays as [1, 2, 3], objects as { a: 1 }, an uncaught error as Uncaught TypeError: message (Chrome and Node wording).

Hints

Saved automatically