Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 28 additions & 0 deletions apps/web/src/hooks/useStableCallback.browser.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import { useLayoutEffect } from "react";
import { describe, expect, it } from "vite-plus/test";

import { render } from "../../test/render";
import { useStableCallback } from "./useStableCallback";

function Child({ value, onLayout }: { value: string; onLayout: (childValue: string) => void }) {
useLayoutEffect(() => {
onLayout(value);
}, [value, onLayout]);
return null;
}

function Parent({ value, seen }: { value: string; seen: string[] }) {
const read = useStableCallback((childValue: string) => seen.push(`${childValue}->${value}`));
return <Child value={value} onLayout={read} />;
}

describe("useStableCallback", () => {
// Child layout effects run before the parent's, so a position restore in a
// child must still reach the handler of the render it commits with.
it("calls the committing render's function from a child layout effect", async () => {
const seen: string[] = [];
await using screen = await render(<Parent value="first" seen={seen} />, { router: false });
await screen.rerender(<Parent value="second" seen={seen} />);
expect(seen).toEqual(["first->first", "second->second"]);
});
});
6 changes: 4 additions & 2 deletions apps/web/src/hooks/useStableCallback.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
import { useLayoutEffect, useRef, useState } from "react";
import { useInsertionEffect, useRef, useState } from "react";

/** Call only from handlers and effects; render sees the previous commit's fn. */
export function useStableCallback<Args extends ReadonlyArray<unknown>, Result>(
fn: (...args: Args) => Result,
): (...args: Args) => Result {
const latest = useRef(fn);
useLayoutEffect(() => {
// Insertion effects run before every layout effect in the commit, so a
// child's layout effect already calls this render's fn.
useInsertionEffect(() => {
latest.current = fn;
});
const [stable] = useState(
Expand Down
Loading