Skip to content

Commit e289070

Browse files
authored
refactor(Grid): use useSyncExternalStore for breakpoint subscriptions (#59774)
* refactor(Grid): use useSyncExternalStore for breakpoint subscriptions * test: fix test case * fix: update
1 parent a7cd6df commit e289070

6 files changed

Lines changed: 306 additions & 24 deletions

File tree

‎components/_util/__tests__/responsiveObserve.test.tsx‎

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,4 +48,42 @@ describe('Test ResponsiveObserve', () => {
4848
instance?.unsubscribe(token);
4949
}
5050
});
51+
52+
it('keeps the observer and unchanged snapshots stable', () => {
53+
const responsiveRef = React.createRef<ReturnType<typeof useResponsiveObserver>>();
54+
const Demo = () => {
55+
responsiveRef.current = useResponsiveObserver();
56+
return null;
57+
};
58+
const { rerender } = render(<Demo />);
59+
const instance = responsiveRef.current!;
60+
const getSnapshot = instance.getSnapshot!;
61+
const getServerSnapshot = instance.getServerSnapshot!;
62+
const initialSnapshot = getSnapshot();
63+
expect(initialSnapshot).toMatchObject({ xs: true });
64+
expect(instance.matchHandlers).toEqual({});
65+
expect(getServerSnapshot()).toBeUndefined();
66+
67+
const subscriber = jest.fn();
68+
const token = instance.subscribe(subscriber);
69+
const snapshot = getSnapshot()!;
70+
expect(snapshot).toBe(initialSnapshot);
71+
72+
rerender(<Demo />);
73+
expect(responsiveRef.current).toBe(instance);
74+
expect(getSnapshot()).toBe(snapshot);
75+
76+
instance.dispatch({ ...snapshot });
77+
expect(getSnapshot()).toBe(snapshot);
78+
expect(subscriber).toHaveBeenCalledTimes(1);
79+
80+
instance.dispatch({ ...snapshot, xs: !snapshot.xs });
81+
expect(getSnapshot()).not.toBe(snapshot);
82+
expect(getSnapshot()?.xs).toBe(!snapshot.xs);
83+
expect(getServerSnapshot()).toBeUndefined();
84+
expect(snapshot.xs).toBe(true);
85+
expect(subscriber).toHaveBeenCalledTimes(2);
86+
87+
instance.unsubscribe(token);
88+
});
5189
});

‎components/_util/responsiveObserver.ts‎

Lines changed: 25 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -78,6 +78,8 @@ export const matchScreen = (screens: ScreenMap, screenSizes?: ScreenSizeMap) =>
7878

7979
interface ResponsiveObserverType {
8080
responsiveMap: BreakpointMap;
81+
getSnapshot?: () => ScreenMap | undefined;
82+
getServerSnapshot?: () => ScreenMap | undefined;
8183
dispatch: (map: ScreenMap) => boolean;
8284
subscribe: (func: SubscribeFunc) => number;
8385
unsubscribe: (token: number) => void;
@@ -94,21 +96,35 @@ interface ResponsiveObserverType {
9496

9597
const useResponsiveObserver = () => {
9698
const [, token] = useToken();
97-
const responsiveMap = getResponsiveMap(validateBreakpoints(token));
99+
const { xs, sm, md, lg, xl, xxl, xxxl } = getResponsiveMap(validateBreakpoints(token));
98100

99101
// To avoid repeat create instance, we add `useMemo` here.
100102
return React.useMemo<ResponsiveObserverType>(() => {
103+
const responsiveMap = { xs, sm, md, lg, xl, xxl, xxxl };
101104
const subscribers = new Map<number, SubscribeFunc>();
102105
let subUid = -1;
103-
let screens: Partial<Record<Breakpoint, boolean>> = {};
106+
let screens: ScreenMap | undefined;
104107
return {
105108
responsiveMap,
106109
matchHandlers: {},
110+
getSnapshot() {
111+
// Read client breakpoints before the first commit without registering listeners in render.
112+
screens ??= Object.fromEntries(
113+
Object.entries(responsiveMap).map<[string, boolean]>(([screen, query]) => [
114+
screen,
115+
window.matchMedia(query).matches,
116+
]),
117+
);
118+
return screens;
119+
},
120+
getServerSnapshot: () => undefined,
107121
dispatch(pointMap: ScreenMap) {
108-
screens = pointMap;
109-
subscribers.forEach((func) => {
110-
func(screens);
111-
});
122+
if (!screens || responsiveArray.some((screen) => screens?.[screen] !== pointMap[screen])) {
123+
screens = pointMap;
124+
subscribers.forEach((func) => {
125+
func(pointMap);
126+
});
127+
}
112128
return subscribers.size >= 1;
113129
},
114130
subscribe(func: SubscribeFunc): number {
@@ -117,7 +133,8 @@ const useResponsiveObserver = () => {
117133
}
118134
subUid += 1;
119135
subscribers.set(subUid, func);
120-
func(screens);
136+
// Register initializes all breakpoints before notifying the first subscriber.
137+
func(screens!);
121138
return subUid;
122139
},
123140
unsubscribe(paramToken: number) {
@@ -149,7 +166,7 @@ const useResponsiveObserver = () => {
149166
subscribers.clear();
150167
},
151168
};
152-
}, [responsiveMap]);
169+
}, [xs, sm, md, lg, xl, xxl, xxxl]);
153170
};
154171

155172
export default useResponsiveObserver;

‎components/descriptions/__tests__/hooks.test.tsx‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ describe('Descriptions.Hooks', () => {
1717
</Descriptions.Item>,
1818
);
1919

20-
return <p>{(items[0] as any).key}</p>;
20+
return <p>{items[0].key}</p>;
2121
};
2222

2323
const { container } = render(<Demo />);
Lines changed: 213 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,213 @@
1+
import React from 'react';
2+
import { renderToString } from 'react-dom/server';
3+
4+
import { Row } from '..';
5+
import { act, render } from '../../../tests/utils';
6+
import ConfigProvider from '../../config-provider';
7+
import useBreakpoint from '../hooks/useBreakpoint';
8+
9+
describe('useBreakpoint', () => {
10+
const originalMatchMedia = window.matchMedia;
11+
let mediaQueries: Map<string, MediaQueryList>;
12+
let matchedQueries: Set<string>;
13+
14+
beforeEach(() => {
15+
mediaQueries = new Map();
16+
matchedQueries = new Set(['(max-width: 575px)']);
17+
window.matchMedia = jest.fn((query: string) => {
18+
if (!mediaQueries.has(query)) {
19+
const mql = Object.assign(new EventTarget(), {
20+
media: query,
21+
matches: matchedQueries.has(query),
22+
}) as MediaQueryList;
23+
jest.spyOn(mql, 'addEventListener');
24+
jest.spyOn(mql, 'removeEventListener');
25+
mediaQueries.set(query, mql);
26+
}
27+
return mediaQueries.get(query)!;
28+
});
29+
});
30+
31+
afterEach(() => {
32+
jest.restoreAllMocks();
33+
window.matchMedia = originalMatchMedia;
34+
});
35+
36+
const changeMedia = (query: string, matches: boolean) => {
37+
const mql = mediaQueries.get(query)!;
38+
Object.assign(mql, { matches });
39+
act(() => {
40+
mql.dispatchEvent(Object.assign(new Event('change'), { matches }));
41+
});
42+
};
43+
44+
it('provides client breakpoints on the first commit', () => {
45+
const committed = jest.fn();
46+
const Demo: React.FC = () => {
47+
const screens = useBreakpoint();
48+
React.useLayoutEffect(() => {
49+
committed(screens);
50+
}, [screens]);
51+
return null;
52+
};
53+
54+
render(<Demo />);
55+
expect(committed.mock.calls[0][0]).toMatchObject({ xs: true, md: false });
56+
});
57+
58+
it('updates breakpoints without resubscribing or rendering unchanged snapshots', () => {
59+
const rendered = jest.fn();
60+
const Demo: React.FC = () => {
61+
const screens = useBreakpoint();
62+
rendered(screens);
63+
return <span>{JSON.stringify(screens)}</span>;
64+
};
65+
const { container, rerender, unmount } = render(<Demo />);
66+
expect(JSON.parse(container.textContent!)).toMatchObject({ xs: true, md: false });
67+
const matchMediaCalls = jest.mocked(window.matchMedia).mock.calls.length;
68+
69+
changeMedia('(min-width: 768px)', true);
70+
expect(JSON.parse(container.textContent!)).toMatchObject({ md: true });
71+
72+
const renderCount = rendered.mock.calls.length;
73+
changeMedia('(min-width: 768px)', true);
74+
expect(rendered).toHaveBeenCalledTimes(renderCount);
75+
76+
rerender(<Demo />);
77+
expect(window.matchMedia).toHaveBeenCalledTimes(matchMediaCalls);
78+
79+
unmount();
80+
mediaQueries.forEach((mql) => {
81+
expect(mql.removeEventListener).toHaveBeenCalledTimes(
82+
jest.mocked(mql.addEventListener).mock.calls.length,
83+
);
84+
});
85+
});
86+
87+
it('reads the latest breakpoints on parent renders when refresh is disabled', () => {
88+
const rendered = jest.fn();
89+
const Demo: React.FC<{ refresh: boolean }> = (props) => {
90+
const { refresh } = props;
91+
const screens = useBreakpoint(refresh);
92+
rendered(screens);
93+
return <span>{JSON.stringify(screens)}</span>;
94+
};
95+
const { container, rerender } = render(<Demo refresh={false} />);
96+
const renderCount = rendered.mock.calls.length;
97+
const matchMediaCalls = jest.mocked(window.matchMedia).mock.calls.length;
98+
expect(container.textContent).toBe('{}');
99+
100+
changeMedia('(min-width: 768px)', true);
101+
expect(rendered).toHaveBeenCalledTimes(renderCount);
102+
expect(container.textContent).toBe('{}');
103+
104+
rerender(<Demo refresh={false} />);
105+
expect(JSON.parse(container.textContent!)).toMatchObject({ md: true });
106+
107+
rerender(<Demo refresh />);
108+
changeMedia('(min-width: 768px)', false);
109+
expect(JSON.parse(container.textContent!)).toMatchObject({ md: false });
110+
expect(window.matchMedia).toHaveBeenCalledTimes(matchMediaCalls);
111+
112+
rerender(<Demo refresh={false} />);
113+
const disabledRenderCount = rendered.mock.calls.length;
114+
changeMedia('(min-width: 768px)', true);
115+
expect(rendered).toHaveBeenCalledTimes(disabledRenderCount);
116+
117+
rerender(<Demo refresh={false} />);
118+
expect(JSON.parse(container.textContent!)).toMatchObject({ md: true });
119+
});
120+
121+
it('updates subscriptions when breakpoint tokens change', () => {
122+
const Demo: React.FC = () => <span>{JSON.stringify(useBreakpoint())}</span>;
123+
const { container, rerender } = render(
124+
<ConfigProvider theme={{ token: { colorPrimary: '#1677ff' } }}>
125+
<Demo />
126+
</ConfigProvider>,
127+
);
128+
const previousQuery = mediaQueries.get('(min-width: 768px)')!;
129+
expect(JSON.parse(container.textContent!)).toMatchObject({ md: false });
130+
131+
const matchMediaCalls = jest.mocked(window.matchMedia).mock.calls.length;
132+
rerender(
133+
<ConfigProvider theme={{ token: { colorPrimary: '#ff0000' } }}>
134+
<Demo />
135+
</ConfigProvider>,
136+
);
137+
expect(window.matchMedia).toHaveBeenCalledTimes(matchMediaCalls);
138+
139+
matchedQueries.add('(min-width: 800px)');
140+
rerender(
141+
<ConfigProvider theme={{ token: { screenMD: 800, screenMDMin: 800 } }}>
142+
<Demo />
143+
</ConfigProvider>,
144+
);
145+
expect(JSON.parse(container.textContent!)).toMatchObject({ md: true });
146+
expect(previousQuery.removeEventListener).toHaveBeenCalledTimes(
147+
jest.mocked(previousQuery.addEventListener).mock.calls.length,
148+
);
149+
150+
changeMedia('(min-width: 800px)', false);
151+
expect(JSON.parse(container.textContent!)).toMatchObject({ md: false });
152+
});
153+
154+
it('retains the latest subscribed breakpoints across token changes when refresh is disabled', () => {
155+
const Demo: React.FC = () => <span>{JSON.stringify(useBreakpoint(false))}</span>;
156+
const renderDemo = (screenMD: number) => (
157+
<ConfigProvider theme={{ token: { screenMD, screenMDMin: screenMD } }}>
158+
<Demo />
159+
</ConfigProvider>
160+
);
161+
const { container, rerender } = render(renderDemo(768));
162+
163+
rerender(renderDemo(768));
164+
expect(JSON.parse(container.textContent!)).toMatchObject({ xs: true, md: false });
165+
166+
changeMedia('(min-width: 768px)', true);
167+
expect(JSON.parse(container.textContent!)).toMatchObject({ md: false });
168+
169+
rerender(renderDemo(800));
170+
expect(JSON.parse(container.textContent!)).toMatchObject({ xs: true, md: true });
171+
172+
rerender(renderDemo(800));
173+
expect(JSON.parse(container.textContent!)).toMatchObject({ xs: true, md: false });
174+
});
175+
176+
it.each([undefined, { md: true }] as const)(
177+
'hydrates with the same default screens as the server: %p',
178+
(defaultScreens) => {
179+
const rendered = jest.fn();
180+
const Demo: React.FC = () => {
181+
const screens = useBreakpoint(true, defaultScreens);
182+
rendered(screens);
183+
return <span>{JSON.stringify(screens)}</span>;
184+
};
185+
const container = document.createElement('div');
186+
container.innerHTML = renderToString(<Demo />);
187+
expect(container.textContent).toBe(JSON.stringify(defaultScreens ?? {}));
188+
expect(window.matchMedia).not.toHaveBeenCalled();
189+
const serverRenderCount = rendered.mock.calls.length;
190+
const onRecoverableError = jest.fn();
191+
192+
const { unmount } = render(<Demo />, { container, hydrate: true, onRecoverableError });
193+
expect(rendered.mock.calls[serverRenderCount][0]).toEqual(defaultScreens ?? {});
194+
expect(onRecoverableError).not.toHaveBeenCalled();
195+
expect(JSON.parse(container.textContent!)).toMatchObject({ xs: true, md: false });
196+
unmount();
197+
},
198+
);
199+
200+
it('preserves the null default used by responsive gutters during hydration', () => {
201+
const Demo: React.FC = () => <Row gutter={{ xs: 8, md: 24 }} />;
202+
const container = document.createElement('div');
203+
container.innerHTML = renderToString(<Demo />);
204+
expect(container.firstElementChild).toHaveStyle({ marginInline: '-12px' });
205+
expect(window.matchMedia).not.toHaveBeenCalled();
206+
const onRecoverableError = jest.fn();
207+
208+
const { unmount } = render(<Demo />, { container, hydrate: true, onRecoverableError });
209+
expect(onRecoverableError).not.toHaveBeenCalled();
210+
expect(container.firstElementChild).toHaveStyle({ marginInline: '-4px' });
211+
unmount();
212+
});
213+
});
Lines changed: 28 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,33 +1,46 @@
1-
import { useRef } from 'react';
2-
import { useLayoutEffect } from '@rc-component/util';
1+
import { useCallback, useRef, useState, useSyncExternalStore } from 'react';
32

4-
import { useForceUpdate } from '../../_util/hooks';
53
import type { ScreenMap } from '../../_util/responsiveObserver';
64
import useResponsiveObserver from '../../_util/responsiveObserver';
75

86
function useBreakpoint(refreshOnChange: boolean, defaultScreens: null): ScreenMap | null;
97
function useBreakpoint(refreshOnChange?: boolean, defaultScreens?: ScreenMap): ScreenMap;
10-
118
function useBreakpoint(
129
refreshOnChange = true,
1310
defaultScreens: ScreenMap | null = {} as ScreenMap,
1411
): ScreenMap | null {
12+
const [initialScreens] = useState<ScreenMap>(defaultScreens as ScreenMap);
1513
const screensRef = useRef<ScreenMap | null>(defaultScreens);
16-
const [, forceUpdate] = useForceUpdate();
1714
const responsiveObserver = useResponsiveObserver();
1815

19-
useLayoutEffect(() => {
20-
const token = responsiveObserver.subscribe((supportScreens) => {
21-
screensRef.current = supportScreens;
22-
if (refreshOnChange) {
23-
forceUpdate();
24-
}
25-
});
16+
const subscribe = useCallback(
17+
(onStoreChange: () => void) => {
18+
const token = responsiveObserver.subscribe((supportScreens) => {
19+
screensRef.current = supportScreens;
20+
onStoreChange();
21+
});
22+
return () => {
23+
responsiveObserver.unsubscribe(token);
24+
};
25+
},
26+
[responsiveObserver],
27+
);
28+
29+
const getSnapshot = useCallback(() => {
30+
if (refreshOnChange) {
31+
return responsiveObserver.getSnapshot?.() ?? initialScreens;
32+
}
33+
return initialScreens;
34+
}, [responsiveObserver, refreshOnChange, initialScreens]);
35+
36+
const getServerSnapshot = useCallback(() => {
37+
return responsiveObserver.getServerSnapshot?.() ?? initialScreens;
38+
}, [responsiveObserver, initialScreens]);
2639

27-
return () => responsiveObserver.unsubscribe(token);
28-
}, [refreshOnChange]);
40+
const screens = useSyncExternalStore<ScreenMap>(subscribe, getSnapshot, getServerSnapshot);
2941

30-
return screensRef.current;
42+
// Disabled refresh still exposes the latest breakpoints on the next parent render.
43+
return refreshOnChange ? screens : screensRef.current;
3144
}
3245

3346
export default useBreakpoint;

0 commit comments

Comments
 (0)