Skip to content

Commit 5f7d52c

Browse files
fix(web): stable callbacks refresh before layout effects read them
Child layout effects run before the parent's, so useStableCallback still called the previous render's function there. After a thread switch with find open, the position restore's navigation reached the old visit and left the shown thread following. The ref now refreshes in an insertion effect, which runs before every layout effect in the commit. Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent 28df7a2 commit 5f7d52c

2 files changed

Lines changed: 32 additions & 2 deletions

File tree

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
import { useLayoutEffect } from "react";
2+
import { describe, expect, it } from "vite-plus/test";
3+
4+
import { render } from "../../test/render";
5+
import { useStableCallback } from "./useStableCallback";
6+
7+
function Child({ value, onLayout }: { value: string; onLayout: (childValue: string) => void }) {
8+
useLayoutEffect(() => {
9+
onLayout(value);
10+
}, [value, onLayout]);
11+
return null;
12+
}
13+
14+
function Parent({ value, seen }: { value: string; seen: string[] }) {
15+
const read = useStableCallback((childValue: string) => seen.push(`${childValue}->${value}`));
16+
return <Child value={value} onLayout={read} />;
17+
}
18+
19+
describe("useStableCallback", () => {
20+
// Child layout effects run before the parent's, so a position restore in a
21+
// child must still reach the handler of the render it commits with.
22+
it("calls the committing render's function from a child layout effect", async () => {
23+
const seen: string[] = [];
24+
await using screen = await render(<Parent value="first" seen={seen} />, { router: false });
25+
await screen.rerender(<Parent value="second" seen={seen} />);
26+
expect(seen).toEqual(["first->first", "second->second"]);
27+
});
28+
});

‎apps/web/src/hooks/useStableCallback.ts‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,13 @@
1-
import { useLayoutEffect, useRef, useState } from "react";
1+
import { useInsertionEffect, useRef, useState } from "react";
22

33
/** Call only from handlers and effects; render sees the previous commit's fn. */
44
export function useStableCallback<Args extends ReadonlyArray<unknown>, Result>(
55
fn: (...args: Args) => Result,
66
): (...args: Args) => Result {
77
const latest = useRef(fn);
8-
useLayoutEffect(() => {
8+
// Insertion effects run before every layout effect in the commit, so a
9+
// child's layout effect already calls this render's fn.
10+
useInsertionEffect(() => {
911
latest.current = fn;
1012
});
1113
const [stable] = useState(

0 commit comments

Comments
 (0)