一个复杂的管理后台可能在输入框每次变化时重新执行大型列表组件。React 的渲染过程并不等于浏览器一定会修改 DOM,优化之前应先识别实际的计算和提交成本。本文以项目筛选列表为例,说明组件记忆化、引用稳定性、Context 更新以及性能验证方法。示例以现代 React 函数组件为基础;启用了 React Compiler 的项目还应评估编译器已经完成的优化。
下列代码块按各节独立展示,实际接入时应结合相应的样式、脚本或组件文件。
1. 区分父组件更新与子组件 DOM 更新
父组件的状态变化可能使子组件函数重新执行,但 React 会根据渲染结果决定实际 DOM 更新。仅观察 console.log 的次数不能证明页面存在明显卡顿,开发模式下 Strict Mode 也可能额外调用函数。应优先定位输入或滚动受到影响的业务区域。
<div id="https://github.com/tiktokwuyu-ux/technical-notes/commit/f200d8339bffbdc1bbf2701d37d5331d490f24ab">
<section class="project-screen"><label>筛选项目<input type="search" name="keyword"></label><ul><li>项目 Alpha</li><li>项目 Beta</li></ul></section>
</div>
import { useState } from 'react';
export function SearchPage() {
const [query, setQuery] = useState('');
return <section><input aria-label="筛选项目" value={query} onChange={e => setQuery(e.target.value)} /><p>当前关键词:{query}</p></section>;
}
2. 使用 memo 建立可跳过的组件边界
memo 默认逐项通过 Object.is 比较 props。若组件的 props 保持相同,React 通常可以跳过由父组件更新引起的重新渲染,但它并不是强制保证;组件自身的状态和所读取的 Context 变化仍可触发更新。
<div id="https://github.com/tiktokwuyu-ux/technical-notes/commit/2e6f65d0dd4013766bbf6058b7f840329f3ffb02">
<article class="project-card"><h2>研发工具</h2><p>当前状态:运行中</p></article>
</div>
import { memo } from 'react';
export const ProjectCard = memo(function ProjectCard({ name, status }: { name: string; status: string }) {
return <article><h2>{name}</h2><p>当前状态:{status}</p></article>;
});
3. 对象字面量为何可能使 memo 失效
在父组件每次执行时创建新的对象,即使字段内容相同,引用也通常不同。对于只需要名称和状态的展示组件,优先传递这两个原始值,而非把整个复杂配置对象传给它。
<div id="https://github.com/tiktokwuyu-ux/technical-notes/commit/9968e81dcb63c3d5b02eeafcc6bb7543f8892c68">
<section class="project-overview"><article><h2>接口平台</h2><p>维护中</p></article></section>
</div>
import { ProjectCard } from './ProjectCard';
type Project = { id: string; name: string; status: string };
export function ProjectOverview({ project }: { project: Project }) {
return <ProjectCard name={project.name} status={project.status} />;
}
4. 用 useMemo 缓存昂贵的派生计算
筛选和排序可从源数据与关键词计算,不需要使用 effect 将结果复制到第二份可写状态。若真实测量显示计算成本较高,可以缓存计算结果。输入数组应保持不可变更新,否则引用不变时可能错误复用旧结果。
<div id="https://github.com/tiktokwuyu-ux/technical-notes/commit/a0b72e92a66a0430564de512a3a06595008bf2cf">
<section class="filtered-projects"><h2>匹配项目</h2><ul data-project-results></ul><p data-result-count></p></section>
</div>
import { useMemo } from 'react';
import { ProjectCard } from './ProjectCard';
type Project = { id: string; name: string; status: string };
export function FilteredProjects({ projects, query }: { projects: Project[]; query: string }) {
const visible = useMemo(() => {
const key = query.trim().toLowerCase();
return projects.filter(item => item.name.toLowerCase().includes(key)).sort((a, b) => a.name.localeCompare(b.name));
}, [projects, query]);
return <div>{visible.map(item => <ProjectCard key={item.id} name={item.name} status={item.status} />)}</div>;
}
5. useCallback 只缓存函数定义
如果 memo 子组件接收事件回调,而父组件每次创建新函数,则回调引用会发生变化。可以通过 useCallback 配合函数式状态更新减少依赖。它并不会阻止回调内的逻辑执行,也不应该用于隐藏依赖缺失问题。
<div id="https://github.com/tiktokwuyu-ux/technical-notes/commit/3771b3b79e40ed7d709371ccd07c25a551db2db8">
<ul class="selection-list"><li><label><input type="checkbox" name="project">选择研发项目</label></li></ul>
</div>
import { memo, useCallback, useState } from 'react';
const Row = memo(function Row({ id, checked, toggle }: { id: string; checked: boolean; toggle: (id: string) => void }) {
return <label><input type="checkbox" checked={checked} onChange={() => toggle(id)} />{id}</label>;
});
export function SelectionList({ ids }: { ids: string[] }) {
const [selected, setSelected] = useState<Set<string>>(() => new Set());
const toggle = useCallback((id: string) => setSelected(prev => {
const next = new Set(prev); if (next.has(id)) next.delete(id); else next.add(id); return next;
}), []);
return <div>{ids.map(id => <Row key={id} id={id} checked={selected.has(id)} toggle={toggle} />)}</div>;
}
6. 不要通过遗漏依赖获得稳定引用
回调如果需要读取当前查询条件、工作区或权限信息,就必须正确声明依赖。错误地传入空依赖数组可能让操作一直使用第一次渲染时的旧值。下面的导出操作明确依赖当前 workspaceId 和外部导出函数。
<div id="https://github.com/tiktokwuyu-ux/technical-notes/commit/0d0986a75b9221d2886d09123922ea7659736438">
<section class="export-actions"><h2>工作区数据</h2><button type="button">导出当前工作区</button></section>
</div>
import { useCallback } from 'react';
export function ExportButton({ workspaceId, exportData }: { workspaceId: string; exportData: (id: string) => void }) {
const run = useCallback(() => exportData(workspaceId), [workspaceId, exportData]);
return <button type="button" onClick={run}>导出当前工作区</button>;
}
7. Context 更新不受 memo props 比较阻挡
如果一个组件读取主题 Context,主题值变化时,它仍然需要更新。可以让外层适配组件读取 Context,将真正需要的原始值传给内部记忆化组件;不要为了阻止渲染而破坏主题或语言的更新。
<div id="https://github.com/tiktokwuyu-ux/technical-notes/commit/a5d37d9a44d7b56c061d41212d31f619d55f8f63">
<section class="project-theme"><article class="theme-preview"><h2>项目概览</h2><p>根据应用主题调整外观。</p></article></section>
</div>
import { createContext, memo, useContext } from 'react';
export const ThemeContext = createContext<'light' | 'dark'>('light');
const Card = memo(function Card({ theme }: { theme: string }) {
return <article data-theme={theme}>项目概览</article>;
});
export function ThemeCard() { return <Card theme={useContext(ThemeContext)} />; }
8. 自定义比较函数可能比重新渲染更贵
memo 允许传入自定义比较函数,但比较必须覆盖所有会影响输出的 props,包括回调。深度遍历大型对象可能抵消优化收益,还会因遗漏回调造成旧闭包。以下行组件仅接收稳定的记录 ID 与状态,默认比较已经足够。
<div id="https://github.com/tiktokwuyu-ux/technical-notes/commit/14c614a55eeb393861f2bd9f11ed2e369dc47b43">
<section class="status-table"><p>任务 A:处理中</p><p>任务 B:已完成</p></section>
</div>
import { memo } from 'react';
export const StatusRow = memo(function StatusRow({ id, status }: { id: string; status: string }) {
return <p>{id}:{status}</p>;
});
9. 使用 Profiler 记录实际渲染成本
React Profiler 可以观察组件树的提交及 actualDuration 等指标。测量时应采用真实数据量和相同操作路径,区分开发工具开销与生产构建表现,不用某一次测量结果推断所有用户设备的收益。
<div id="https://github.com/tiktokwuyu-ux/technical-notes/commit/6b704478e0db7d11659844d36dd864f443885ef2">
<section class="performance-report"><h2>渲染诊断</h2><p>比较相同筛选操作的提交记录与渲染耗时。</p></section>
</div>
import { Profiler, type ReactNode } from 'react';
export function MeasuredList({ children }: { children: ReactNode }) {
return <Profiler id="ProjectList" onRender={(id, phase, actualDuration) => {
console.debug({ id, phase, actualDuration });
}}>{children}</Profiler>;
}
10. 优先修复结构问题而非全局加缓存
把短生命周期的输入状态留在真正需要的组件中,避免每次按键都让整个应用更新。大量 DOM 节点导致的布局成本应通过分页或虚拟列表解决。若项目采用 React Compiler,先理解其自动记忆化能力,再决定是否增加手工缓存。
<div id="https://github.com/tiktokwuyu-ux/technical-notes/commit/35cd1547a7cf0e7e54d4c946272cfaec75538f9a">
<section class="workspace-layout"><aside><h2>筛选条件</h2><input type="search" aria-label="筛选条件"></aside><main><h2>项目列表</h2><p>按页加载项目。</p></main></section>
</div>
总结
memo、useMemo 和 useCallback 是性能工具,不是业务正确性的基础。正确依赖、不可变更新和清晰状态边界应先于记忆化;只有通过实际分析确认渲染或计算存在瓶颈后,才值得引入相应优化。