一行 5000 个项目——无需虚拟化
ScrollMenu 并保持流畅——原生 overflow 滚动负责移动,IntersectionObserver 负责观察,而 React 基本什么都不用做。5,000 items, no virtualization
拖拽轨道或用箭头翻页——5000 张卡片每一个都是真实 DOM 节点;没有任何窗口化。
哪些工作没有发生
滚动从不进入 React。这条轨道是真正的 overflow 容器:滚轮与触摸原生地滚动它,而拖拽接线只是给 scrollContainer.current.scrollLeft 赋值——没有 state,也没有每帧重新渲染。可见性由单个 IntersectionObserver 实例观察全部 5000 个项目元素;回调批量到达,只有用 useIsVisible 订阅了的组件会在它们自己的项目翻转变动时更新。任何地方都没有逐项的滚动计算。
这个 story 调了什么
Card 被 React.memo 包裹,带一个基于 selected 与 title 的比较器,这样选中一张卡片就不会协调其余 4999 张。可见性读数经过 useDeferredValue:在一次翻页跳转后,数百个项目同时翻转状态,延迟处理让这波更新避开引发它的那次交互的关键路径。noPolyfill={true} 让程序化滚动使用浏览器自身的 scrollIntoView,而不是平滑滚动补丁。拖拽用的是与鼠标拖拽示例相同的 DragDealer 模式。
本页坦言的一个取舍
上面的演示轨道没有服务端渲染:5000 张卡片大约会序列化成 1 MB 的 HTML,所以轨道只以客户端方式挂载,隐藏在一个高度匹配的占位符后面,由此没有布局偏移。这才是这个规模真正的代价——浏览器能轻松处理 5000 个活跃节点,但把它们作为 SSR 载荷送出是另一回事。在几万节点的某个量级,内存与初次渲染成本也会追上来;从那里开始,窗口化就不再是可选项了。
注意
- 5000 张卡片的 DOM 只在挂载时构建一次——
React.memo让之后父组件的渲染对每张卡片都成为空操作。 - 箭头大约一次翻一个视口,因此纯靠箭头横穿整条轨道本来就慢——拖拽轻拂或
scrollToItem跳转更适合这个规模。 - 箭头仍运行在
useIsVisible('first')与useIsVisible('last')上——与十项的菜单相同的观察机制,只是项目数是它的 500 倍。
完整源码
完整且可直接复制粘贴——这正是背后这份文件的 可在 Storybook 中实时编辑的版本.
import 'react-horizontal-scrolling-menu/dist/styles.css';
import styled from '@emotion/styled';
import React from 'react';
import {
type publicApiType,
ScrollMenu,
VisibilityContext,
} from 'react-horizontal-scrolling-menu';
const ITEMS = 5000;
export function Performance() {
const [items] = React.useState(() => getItems(ITEMS));
const [selected, setSelected] = React.useState<string[]>([]);
// NOTE: for drag by mouse
const dragState = React.useRef(new DragDealer());
const handleDrag = React.useCallback(
({ scrollContainer }: publicApiType) =>
(ev: React.MouseEvent) =>
dragState.current.dragMove(ev, (posDiff) => {
if (scrollContainer.current) {
scrollContainer.current.scrollLeft += posDiff;
}
}),
[],
);
const onMouseDown = React.useCallback(
() => dragState.current.dragStart,
[dragState],
);
const onMouseUp = React.useCallback(
() => dragState.current.dragStop,
[dragState],
);
const handleItemClick = React.useCallback((itemId: string) => {
if (dragState.current.dragging) {
return false;
}
setSelected((currentSelected: string[]) =>
currentSelected.includes(itemId)
? currentSelected.filter((el) => el !== itemId)
: currentSelected.concat(itemId),
);
}, []);
return (
<>
<div style={{ marginBottom: '50px' }}>{ITEMS} items and still fast!</div>
<div onMouseLeave={() => dragState.current.dragStop()}>
<ScrollMenu
LeftArrow={LeftArrow}
RightArrow={RightArrow}
onMouseDown={onMouseDown}
onMouseUp={onMouseUp}
onMouseMove={handleDrag}
onWheel={onWheel}
// better for performance
noPolyfill={true}
>
{items.map(({ id }) => (
<Card
title={id}
itemId={id} // NOTE: itemId is required for track items
key={id}
onClick={handleItemClick}
selected={selected.includes(id)}
/>
))}
</ScrollMenu>
</div>
</>
);
}
export default Performance;
class DragDealer {
clicked: boolean;
dragging: boolean;
position: number;
constructor() {
this.clicked = false;
this.dragging = false;
this.position = 0;
}
public dragStart = (ev: React.MouseEvent) => {
this.position = ev.clientX;
this.clicked = true;
};
public dragStop = () => {
window.requestAnimationFrame(() => {
this.dragging = false;
this.clicked = false;
});
};
public dragMove = (ev: React.MouseEvent, cb: (posDiff: number) => void) => {
const newDiff = this.position - ev.clientX;
const movedEnough = Math.abs(newDiff) > 5;
if (this.clicked && movedEnough) {
this.dragging = true;
}
if (this.dragging && movedEnough) {
this.position = ev.clientX;
cb(newDiff);
}
};
}
const LeftArrow = React.memo(() => {
const visibility = React.useContext<publicApiType>(VisibilityContext);
const isFirstItemVisible = visibility.useIsVisible('first', true);
return (
<Arrow
disabled={isFirstItemVisible}
onClick={() => visibility.scrollPrev()}
testId="left-arrow"
>
Left
</Arrow>
);
});
const RightArrow = React.memo(() => {
const visibility = React.useContext<publicApiType>(VisibilityContext);
const isLastItemVisible = visibility.useIsVisible('last', false);
return (
<Arrow
disabled={isLastItemVisible}
onClick={() => visibility.scrollNext()}
testId="right-arrow"
>
Right
</Arrow>
);
});
function Arrow({
children,
disabled,
onClick,
testId,
}: {
children: React.ReactNode;
disabled: boolean;
onClick: VoidFunction;
testId: string;
}) {
return (
<ArrowButton disabled={disabled} onClick={onClick} data-testid={testId}>
{children}
</ArrowButton>
);
}
const ArrowButton = styled('button')((props) => ({
cursor: 'pointer',
display: 'flex',
flexDirection: 'column',
justifyContent: 'center',
marginBottom: '2px',
opacity: props.disabled ? '0' : '1',
userSelect: 'none',
borderRadius: '6px',
borderWidth: '1px',
}));
const Card = React.memo(
({
onClick,
selected,
title,
itemId,
}: {
onClick: (itemId: string) => void;
selected: boolean;
title: string;
itemId: string;
}) => {
const visibility = React.useContext<publicApiType>(VisibilityContext);
const isVisible = visibility.useIsVisible(itemId, true);
const isVisibleDeffered = React.useDeferredValue(isVisible);
const handleClick = React.useCallback(
() => onClick(itemId),
[itemId, onClick],
);
const onKeyDown = React.useCallback(
(ev: React.KeyboardEvent) => {
ev.code === 'Enter' && handleClick();
},
[handleClick],
);
return (
<CardBody
data-cy={itemId}
onClick={handleClick}
onKeyDown={onKeyDown}
data-testid="card"
role="button"
tabIndex={0}
className="card"
visible={isVisibleDeffered}
selected={selected}
>
<div className="header">
<div>{title}</div>
<div className="visible">
visible: {JSON.stringify(isVisibleDeffered)}
</div>
<div className="selected">selected: {JSON.stringify(!!selected)}</div>
</div>
<div className="background" />
</CardBody>
);
},
(prevProps, nextProps) =>
prevProps.selected === nextProps.selected &&
prevProps.title === nextProps.title,
);
const CardBody = styled('div')<{ selected?: boolean; visible?: boolean }>(
(props) => ({
border: '1px solid',
display: 'inline-block',
margin: '0 10px',
width: '160px',
userSelect: 'none',
borderRadius: '8px',
overflow: 'hidden',
'& .header': {
backgroundColor: 'white',
},
'& .visible': {
backgroundColor: props.visible ? 'transparent' : 'gray',
},
'& .background': {
backgroundColor: props.selected ? 'green' : 'bisque',
height: '200px',
},
}),
);
const getId = (index: number) => `${'test'}${index}`;
const getItems = (count: number) =>
Array(count)
.fill(0)
.map((_, ind) => ({ id: getId(ind) }));
function onWheel(apiObj: publicApiType, ev: React.WheelEvent): void {
// NOTE: no good standart way to distinguish touchpad scrolling gestures
// but can assume that gesture will affect X axis, mouse scroll only Y axis
// of if deltaY too small probably is it touchpad
const isThouchpad = Math.abs(ev.deltaX) !== 0 || Math.abs(ev.deltaY) < 15;
if (isThouchpad) {
ev.stopPropagation();
return;
}
if (ev.deltaY < 0) {
apiObj.scrollNext();
} else {
apiObj.scrollPrev();
}
}