#1532·opentui

`useLayoutEffect` sees the previous commit's layout, not the one it just committed

Author: letrquanCreated Sep 24, 2026Updated Sep 24, 2026

Environment

  • OS: Windows 11 (not platform-specific; reproduces under @opentui/core/testing, no PTY or real terminal needed)
  • Runtime: Bun 1.4.0
  • @opentui/core: 0.5.12 (also the latest published version as of 2026-09-24 -- npm view @opentui/core version -- so there is no separate "does it happen on latest" data point)
  • @opentui/react: 0.5.12
  • react: 19.2.8

Summary

useLayoutEffect is supposed to run after the host tree has been mutated for the current commit and before the next paint, so a synchronous read of a ref's layout inside it reflects that commit. In @opentui/react, it does not: reading a Renderable's .height inside a useLayoutEffect returns the previous commit's value when a sibling mounted/unmounted in the commit the effect is firing for. Layout (Yoga) recalculation only happens during the renderer's own render pass, which runs later (on its own schedule); anything that reads layout between a commit and that next render pass -- including useLayoutEffect, which React runs synchronously right after the commit -- sees the previous layout instead.

This breaks any "measure what just changed, then reposition" pattern -- for example a scrollable view that keeps its newest content pinned to the bottom by measuring total content height (via useLayoutEffect) after a child mounts/unmounts and applying the result as a scroll offset.

Minimal repro

typescript
// repro.tsx -- run with `bun repro.tsx`. Deterministic, no PTY needed.
import { createTestRenderer } from "@opentui/core/testing";
import { createRoot } from "@opentui/react";
import React, { useLayoutEffect, useRef, useState } from "react";

const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
const log: string[] = [];
let setShowSibling: ((v: boolean) => void) | null = null;

function App() {
  const [showSibling, setShow] = useState(false);
  const wrapperRef = useRef<any>(null);
  setShowSibling = setShow;

  useLayoutEffect(() => {
    log.push(`[sync] showSibling=${showSibling}  height measured INSIDE the effect = ${wrapperRef.current?.height}`);
  }, [showSibling]);

  return (
    <box ref={wrapperRef} flexDirection="column">
      <text>anchor</text>
      {showSibling && (
        <box flexDirection="column">
          <text>sib 1</text>
          <text>sib 2</text>
          <text>sib 3</text>
        </box>
      )}
    </box>
  );
}

const { renderer, renderOnce, flush } = await createTestRenderer({ width: 20, height: 10 });
const outsideHeight = () => renderer.root.getChildren()[0]?.height;

const root = createRoot(renderer as any);
root.render(<App />);
await sleep(100);
await renderOnce();
await flush();
log.push(`--- mounted; height measured from OUTSIDE any effect = ${outsideHeight()} ---`);

setShowSibling!(true);
await sleep(100);
await renderOnce();
await flush();
log.push(`--- after setShowSibling(true); height measured from OUTSIDE = ${outsideHeight()} ---`);

setShowSibling!(false);
await sleep(100);
await renderOnce();
await flush();
log.push(`--- after setShowSibling(false); height measured from OUTSIDE = ${outsideHeight()} ---`);

console.log(log.join("\n"));
process.exit(0);

Steps

  1. bun install @opentui/[email protected] @opentui/[email protected] react
  2. Save the snippet above as repro.tsx (exactly as written), run bun repro.tsx.

Expected vs actual

Expected: the [sync] line's measurement matches the "measured from OUTSIDE" line for the same commit (both reflect the sibling that was just mounted/unmounted).

Actual, every run:

[sync] showSibling=false  height measured INSIDE the effect = 0
--- mounted; height measured from OUTSIDE any effect = 1 ---
[sync] showSibling=true  height measured INSIDE the effect = 1
--- after setShowSibling(true); height measured from OUTSIDE = 4 ---
[sync] showSibling=false  height measured INSIDE the effect = 4
--- after setShowSibling(false); height measured from OUTSIDE = 1 ---

Every [sync] reading (inside the effect) is exactly one commit behind the corresponding "measured from OUTSIDE" reading. The outside reading is taken after a sleep(100), not synchronously -- checked directly: the height is already correct after that sleep(100) alone, before renderOnce()/flush() are called, confirming the test renderer's own scheduler recalculates layout on its own timer during the sleep, independent of the React commit.

Notes / possible cause

Read directly from the installed react-reconciler (not assumed): the commit phase calls the host config's mutation methods, then resetAfterCommit(root.containerInfo), and only after that flushLayoutEffects() -- which is what invokes useLayoutEffect callbacks (react-reconciler/cjs/react-reconciler.development.js, flushMutationEffects -> resetAfterCommit -> pendingEffectsStatus = PENDING_LAYOUT_PHASE -> flushLayoutEffects). So resetAfterCommit runs at exactly the right time to fix this: @opentui/react's resetAfterCommit (packages/react/src/reconciler/host-config.ts) currently only calls containerInfo.requestRender(), which schedules a future render pass rather than recalculating layout immediately. If it instead forced a synchronous layout recalculation (the renderer's own calculateLayout/ updateFromLayout path, called elsewhere on its own render-pass timer -- chunk-node-*.js's calculateLayout() calling this.yogaNode.calculateLayout(...)), useLayoutEffect callbacks running immediately afterward would see the current commit's layout instead of the previous one. Confirmed still the case on main, not fixed in an unreleased version.

There is a working, but later-firing, alternative: a Renderable's onSizeChange handler (also documented as firing "during a render pass") DOES report the correct, current height for the same transition -- verified directly, in the same repro shape, the callback logs the correct value (e.g. 4, not the stale 1) immediately after onSizeChange fires, one step after the corresponding useLayoutEffect call for the same state change. It is a real workaround for a consumer that can restructure around an imperative callback instead of useLayoutEffect, but it does not resolve the underlying useLayoutEffect contract violation this report is about.

Background

Found while porting an app's TUI from Ink to OpenTUI: a scroll view that keeps new output pinned to the bottom measures content height in a useLayoutEffect to compute a scroll offset, which is exactly this pattern. Whether it's the actual cause of a symptom seen in that port (unrelated content going blank after a sibling's mount/unmount changed the scroll offset) is not confirmed -- that app's real measurement code defers its read by one tick rather than reading synchronously inside the effect, so it may or may not hit this exact staleness window; not independently re-verified end to end. This bug stands on its own regardless of that connection.

Related issues

  • None found with matching keywords (useLayoutEffect, "stale layout", "measure height ref", "calculateLayout", "scroll to bottom") via gh search issues --repo anomalyco/opentui or gh search prs --repo anomalyco/opentui.
  • Issue #1110 ("alternate-screen: rightmost column stays stale after horizontal resize") is a different trigger (terminal resize, not a React commit) but the same general class of "the renderer's own state is stale relative to what should currently be true" symptom -- worth a mention for a maintainer triaging both.