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
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import type { ComponentType, PropsWithChildren } from "react";
import { memo } from "react";
import { beforeEach, expect, test } from "vitest";
import { render } from "vitest-browser-react";
import { page } from "vitest/browser";
import { flowComponent } from "@/lib/componentFactory/flowComponent";
import { useSlotContext } from "@/lib/slotContext/slotContext";

type SlottedComponentProps = PropsWithChildren<{
slot?: string;
testProp?: string;
}>;

const SlottedComponent = flowComponent("TestComponent", (props) => (
<>{props.children}</>
)) as ComponentType<SlottedComponentProps>;

let consumerRenderCount: number;

const SlotContextConsumer = memo(() => {
consumerRenderCount++;
return <span data-testid="slot">{useSlotContext().TestComponent}</span>;
});

const renderSlotted = (slot: string, testProp: string) => (
<SlottedComponent slot={slot} testProp={testProp}>
<SlotContextConsumer />
</SlottedComponent>
);

beforeEach(() => {
consumerRenderCount = 0;
});

test("slot context consumers do not re-render when an unrelated prop changes", async () => {
const { rerender } = await render(renderSlotted("primary", "a"));
await expect.element(page.getByTestId("slot")).toHaveTextContent("primary");
expect(consumerRenderCount).toBe(1);

await rerender(renderSlotted("primary", "b"));
expect(consumerRenderCount).toBe(1);

await rerender(renderSlotted("secondary", "b"));
await expect.element(page.getByTestId("slot")).toHaveTextContent("secondary");
expect(consumerRenderCount).toBe(2);
});
13 changes: 8 additions & 5 deletions packages/components/src/lib/slotContext/SlotContextProvider.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import type { FC, PropsWithChildren } from "react";
import { memo } from "react";
import { memo, useMemo } from "react";
import type { FlowComponentName } from "@/components/propTypes";
import { slotContext, useSlotContext } from "@/lib/slotContext/slotContext";

Expand All @@ -15,10 +15,13 @@ export const SlotContextProvider: FC<Props> = memo((props) => {
const { slot, component, children } = props;
const parentContext = useSlotContext();

const mergedContext = {
...parentContext,
[component]: slot,
};
const mergedContext = useMemo(
() => ({
...parentContext,
[component]: slot,
}),
[parentContext, component, slot],
);

return <Provider value={mergedContext}>{children}</Provider>;
});
Expand Down
Loading