React 是什么 · 七问7 questions on what React is
React vs Angular、优势、SPA、JSX、虚拟 DOM 与 diff、reconciliation、babel 与 webpack。React vs Angular, the selling points, SPA, JSX, the virtual DOM and diffing, reconciliation, babel and webpack.
这一页有什么On this page8
- 01 什么是 SPAWhat is a SPA?
- 02 React 的优势是什么What are the advantages of React?
- 03 React vs Angular
- 04 什么是 JSXWhat is JSX?
- 05 虚拟 DOM 和 diff 算法What are the virtual DOM and the diffing algorithm?
- 06 什么是 reconciliationWhat is reconciliation?
- 07 React 项目里 babel 和 webpack 干什么What do babel and webpack do in a React project?
- 迁移模式Transfer
- 说清虚拟 DOM 为什么快,以及它「不一定比手写 DOM 快」这层真相Explain why the virtual DOM is fast, and also why it is not always faster than writing DOM calls yourself
- 解释 diff 算法的三条启发式规则,并说明 key 为什么重要Explain the three shortcuts the diffing algorithm takes, and say why key matters
- 分清 SPA 的优点和它带来的三个新问题Tell the benefits of a SPA apart from the three new problems it creates
- 说明 JSX 编译成了什么Say what JSX compiles into
这一组考的是「心智模型」。虚拟 DOM 和 diff 答得空洞(只说「快」)会掉分,答得出「批量 + 最小化真实操作,代价是内存和一次 diff 计算」才算过关。key 那条会直接连到 Q1 里列表渲染的真实代码。This group tests your mental model. Answering "the virtual DOM is fast" and nothing more will cost you points. To pass you have to say what it actually does: it batches updates and keeps real DOM work to a minimum, and it pays for that with memory and one diffing pass. The point about key connects straight to the list rendering code in Q1.
什么是 SPAWhat is a SPA?
#321 What is a SPA
一句话:单页应用 ——只加载一个 HTML, 之后的页面切换由 JS 在前端换内容, 不再向服务器请求整页。
好处:切页面没有白屏刷新、体验接近原生 App、 前后端彻底分离(后端只给 JSON)。
代价(面试重点问这半边):
- 首屏慢—— 要先下载并执行一大包 JS 才能看到内容。 解法是代码分割(
React.lazy,见 #347) 和 SSR。 - SEO 差—— 爬虫拿到的 HTML 是空的
<div id="root"></div>。 解法是 SSR / SSG(Next.js)。 - 路由要自己管—— 前进后退、深链接、刷新后还在当前页, 都得靠
historyAPI 和服务端的 fallback 配置。「刷新 404」就是漏配了 fallback。 - 内存泄漏风险—— 页面不刷新, 定时器和监听器不会被自动清掉。这就是
useEffect必须写清理函数的现实原因。
会追问:「MPA 什么时候更好?」—— 内容型站点(博客、文档、电商详情页), 重 SEO、首屏优先、交互不复杂的。答得出「看场景」比一味夸 SPA 好。
In one line: a single-page application — one HTML document gets loaded, and from then on JS swaps the content on the client instead of asking the server for a whole new page.
Upsides: no white flash when you change pages, it feels close to a native app, and front end and back end are fully separated (the server only returns JSON).
Costs — this is the half they probe:
- Slow first paint — you have to download and run a big JS bundle before anything shows up. The fixes are code splitting (
React.lazy, see #347) and SSR. - Weak SEO — a crawler receives an empty
<div id="root"></div>. The fix is SSR / SSG (Next.js). - You own the routing — back and forward, deep links, staying on the current page after a refresh, all of it rides on the
historyAPI plus a fallback on the server. “404 on refresh” means the fallback is missing. - Memory leaks — the page never reloads, so timers and listeners are never cleared for you. That is the practical reason
useEffectneeds a cleanup function.
Follow-up: “When is an MPA better?” — content sites (blogs, docs, product detail pages) where SEO and first paint matter and the interaction stays simple. “It depends on the case” beats praising SPAs unconditionally.
React 的优势是什么What are the advantages of React?
#320 React advantage
一句话:声明式 + 组件化 + 单向数据流—— 你描述「界面应该长什么样」, React 负责把 DOM 变成那样。
- 声明式—— 你写
{items.map(...)}, 不写「找到 ul、创建 li、appendChild」。省掉的是「怎么从状态 A 变到状态 B」这类过程代码, 而这正是 bug 最多的地方。 - 组件化—— UI 拆成可复用、 可独立测试的单元。
- 单向数据流—— props 往下、事件往上。 出问题时排查路径是确定的: 数据只可能从一个方向来。
- 生态—— Router、 状态库、Next.js、React Native (同一套心智模型能写移动端)。
会追问缺点(一定要准备): 只是个视图库,路由和状态都要自己选,选型成本高; 性能优化要手动(memo /useMemo,React 19 之前没有自动记忆化); JSX 和 hooks 规则对新手有门槛;版本迁移的心智负担不小(class → hooks → Server Components)。
In one line: declarative + component-based + one-way data flow — you describe what the UI should look like and React makes the DOM match.
- Declarative — you write
{items.map(...)}, not “find the ul, create an li, appendChild”. What you drop is the step-by-step code for getting from state A to state B, and that is where most bugs live. - Components — the UI splits into reusable units you can test on their own.
- One-way data flow — props go down, events go up. When something breaks, there is exactly one path to trace: the data can only have come from one direction.
- Ecosystem — Router, state libraries, Next.js, React Native (the same mental model gets you a mobile app).
They will ask for the downsides (have them ready): it is only a view library, so you pick the router and the state layer yourself — the cost of those decisions is real; performance work is manual (memo / useMemo; there was no automatic memoization before React 19); JSX and the hook rules are a hurdle for beginners; and version migrations carry a lot of mental load (class → hooks → Server Components).
React vs Angular
#319 React vs Angular
一句话:React 是库(只管视图,其他自己选); Angular 是框架(路由、HTTP、表单、依赖注入、 测试全都自带)。
| React | Angular | |
|---|---|---|
| 定位 | 库 | 全套框架 |
| 语言 | JS / TS,JSX | TypeScript 强制,HTML 模板 |
| 数据流 | 单向 | 支持双向绑定(ngModel) |
| DOM 策略 | 虚拟 DOM | 增量 DOM + 变更检测 |
| 学习曲线 | 入门低,但选型多 | 入门陡(DI、RxJS、装饰器),之后规范统一 |
| 适合 | 灵活、迭代快、团队愿意自己搭 | 大型企业项目、要求统一规范 |
怎么答得体面:别踩一捧一。说 「React 给自由也给选型负担, Angular 给约定也给学习成本;小而快的项目和需要长期多人维护的大项目, 答案不一样」。
会追问 Vue—— Vue 在两者之间:有官方路由和状态库 (比 React 统一), 但比 Angular 轻;模板语法上手快。
In one line: React is a library (it handles the view, you choose the rest); Angular is a framework (routing, HTTP, forms, dependency injection and testing all come in the box).
| React | Angular | |
|---|---|---|
| What it is | A library | A full framework |
| Language | JS / TS, JSX | TypeScript required, HTML templates |
| Data flow | One-way | Two-way binding available (ngModel) |
| DOM strategy | Virtual DOM | Incremental DOM + change detection |
| Learning curve | Easy to start, but many choices to make | Steep at first (DI, RxJS, decorators), consistent after |
| Fits | Flexible work, fast iteration, a team happy to assemble its own stack | Large enterprise projects that need one standard |
How to answer without picking a fight: do not talk one down to lift the other. Say “React gives you freedom and the burden of choosing; Angular gives you conventions and a learning cost. The answer differs for a small fast project and for a big one many people maintain for years.”
They will ask about Vue — Vue sits between the two: it has an official router and state library (more unified than React) but stays lighter than Angular, and the template syntax is quick to pick up.
什么是 JSXWhat is JSX?
#326 What is JSX
一句话:JavaScript 的语法扩展, 让你在 JS 里写类似 HTML 的结构。浏览器不认识它, 要经过 Babel 编译成普通函数调用。
编译成什么(这是考点): 旧版编译成React.createElement(type, props, ...children);React 17 之后用新的 JSX 转换, 编译成 _jsx(...), 所以不用再手动import React 了。
要说清的几条规则:
- 必须有单一根节点—— 因为函数只能返回一个值。 不想多套
div就用Fragment(见 #338)。 - 属性名用小驼峰——
className(因为class是 JS 关键字)、htmlFor、onClick。 {}里放表达式, 不能放语句 —— 所以条件渲染用三元或&&,不能写if。- JSX 默认转义, 所以天然防 XSS; 要插 HTML 得显式写
dangerouslySetInnerHTML——名字故意起得难听, 就是让你警觉。
会追问:「JSX 是必须的吗?」—— 不是,你可以手写createElement, 只是没人愿意。JSX 的价值是让 「UI 结构」在代码里长得像结构。
In one line: a syntax extension for JavaScript that lets you write HTML-like structure inside JS. The browser does not understand it — Babel compiles it into plain function calls.
What it compiles to (this is the part being tested): old versions produced React.createElement(type, props, ...children); since React 17 the new JSX transform emits _jsx(...), which is why you no longer have to write import React by hand.
The rules you should state clearly:
- One root node is required — a function can only return one value. If you do not want another
div, use aFragment(see #338). - Attribute names are camelCase —
className(becauseclassis a JS keyword),htmlFor,onClick. {}holds an expression, not a statement — so conditional rendering uses a ternary or&&, neverif.- JSX escapes by default, so you get XSS protection for free; injecting raw HTML takes an explicit
dangerouslySetInnerHTML— the name is deliberately ugly so that you stop and think.
Follow-up: “Is JSX mandatory?” — no, you can call createElement yourself, nobody wants to. The value of JSX is that UI structure looks like structure in the code.
虚拟 DOM 和 diff 算法What are the virtual DOM and the diffing algorithm?
#330 Virtual DOM and diffing algorithm
一句话:虚拟 DOM 是用普通 JS 对象描述真实 DOM 的一棵轻量树。 状态变了先在内存里生成新树, 和旧树 diff,算出最小改动,再一次性打到真实 DOM 上。
为什么快 —— 说准这两条:
- 批量—— 十次 state 更新 合并成一次 DOM 操作, 避免十次重排(见 #288)。
- 最小化—— 只改真正变了的属性和节点, 不重建整棵子树。
但要说出这层真相(加分点):虚拟 DOM 不一定比手写 DOM 快—— 精心手写的原生操作永远更快, 虚拟 DOM 还额外付出了「建树 + diff」的开销。它真正的价值是「在保持声明式写法的同时, 性能仍然够好」—— 是可维护性和性能的折中, 不是性能银弹。
diff 的三条启发式规则(把 O(n³) 降到 O(n) 的关键):
- 只比同层,不跨层移动节点。 跨层的话就是删了重建。
- 类型不同直接整棵重建——
div换成span, 子树全部丢弃重做(state 也丢)。 - 同层列表用
key认身份。
key 为什么不能用 index—— 这是 React 面试最实用的一条: 在开头插入或删除一项时, 所有元素的 index 都变了, React 会认为「每一项的内容都变了」, 于是大量误更新; 更糟的是非受控输入框的内容会串到别的行, 因为 DOM 节点被复用了。Q1 那道真题里删除笔记的 bug 就是这个。
In one line: the virtual DOM is a lightweight tree of plain JS objects describing the real DOM. When state changes, React builds a new tree in memory, diffs it against the old one, works out the smallest set of changes, and applies them to the real DOM in one go.
Why it is fast — get these two right:
- Batching — ten state updates collapse into one DOM write, so you avoid ten reflows (see #288).
- Minimising — only the attributes and nodes that really changed get touched; whole subtrees are not rebuilt.
But say this part too — it is the bonus point: the virtual DOM is not necessarily faster than hand-written DOM code — carefully tuned native operations always win, and the virtual DOM pays extra for building a tree and diffing it. Its real value is that you keep the declarative style and performance is still good enough — it is a trade-off between maintainability and performance. It is not the right choice everywhere.
The three diff heuristics (what turns O(n³) into O(n)):
- Compare the same level only; nodes never move across levels. Crossing a level means delete and rebuild.
- A different type rebuilds the whole subtree — swap a
divfor aspanand the subtree is thrown away and redone, state included. - Lists on the same level use
keyfor identity.
Why index must not be the key — the most useful thing you can say in a React interview: insert or delete at the front and every index shifts, so React believes the content of every row changed and does a pile of needless updates; worse, text typed into an uncontrolled input ends up on the wrong row, because the DOM node got reused. The delete-a-note bug in the real Q1 question is exactly this.
什么是 reconciliationWhat is reconciliation?
#353 What is reconciliation
一句话:reconciliation(协调)是「比较新旧虚拟 DOM 树, 决定要对真实 DOM 做哪些操作」的整个过程。 diff 算法是它的一部分。
diff 和 reconciliation 什么关系?这是本题的考点:diff 是「怎么比」的算法, reconciliation 是「比 + 决定 + 提交」的完整流程。 说它们是一回事不算错,但分得清更好。
React 16 之后的 Fiber 架构把这个过程拆成两个阶段 —— 这是必答的:
- render 阶段(可中断)—— 构建 Fiber 树、做 diff、 标记要改什么。这个阶段可以被打断和恢复, 所以高优先级的更新(比如用户输入)能插队。
- commit 阶段(不可中断)—— 把标记好的改动一次性打到真实 DOM 上, 然后跑
useEffect。这一段必须同步完成, 否则用户会看到半渲染的界面。
为什么要能中断?因为老架构(Stack Reconciler)是递归的、一旦开始就停不下来, 大列表更新时会阻塞主线程十几毫秒以上, 输入卡顿。Fiber 用链表 + 循环替代递归, 每处理一小块就检查「有没有更急的事」。这就是「并发特性」的基础(见 #344)。
会追问:「StrictMode 为什么渲染两次?」—— 因为 render 阶段可能被中断和重跑, 所以渲染函数必须是纯的; 两次渲染就是帮你把不纯的地方暴露出来(见 #332)。
In one line: reconciliation is the whole process of comparing the new and old virtual DOM trees and deciding which operations to run on the real DOM. The diff algorithm is one part of it.
How do diff and reconciliation relate? That is the point of the question: diff is the algorithm for how to compare; reconciliation is the full compare, decide and commit flow. Calling them the same thing is not wrong, but telling them apart is better.
The Fiber architecture, from React 16 on, splits the process into two phases — answer this every time:
- Render phase (interruptible) — build the Fiber tree, diff, mark what has to change. This phase can be paused and resumed, which is how a high-priority update such as typing jumps the queue.
- Commit phase (not interruptible) — apply the marked changes to the real DOM in one pass, then run
useEffect. This part must finish synchronously, otherwise users would see a half-rendered screen.
Why does it need to be interruptible? Because the old Stack Reconciler was recursive and could not stop once it started, so a large list update blocked the main thread for tens of milliseconds and typing stuttered. Fiber replaces recursion with a linked list plus a loop, and after each small chunk it checks whether something more urgent came in. This is the foundation of the concurrent features (see #344).
Follow-up: “Why does StrictMode render twice?” — because the render phase can be interrupted and re-run, so the render function has to be pure; the double render is there to expose the impure parts (see #332).
React 项目里 babel 和 webpack 干什么What do babel and webpack do in a React project?
#337 What do we use babel and web pack for in React applications
一句话分工:Babel 负责「翻译」(JSX 和新语法 → 浏览器能懂的 JS);Webpack 负责「打包」(把一堆模块和资源合并成能上线的几个文件)。
- Babel——
@babel/preset-react转 JSX,@babel/preset-env按目标浏览器把 ES2020+ 降级。它只做语法转换, 新 API(Promise、Array.flat)要靠 polyfill 补。这个区分是加分点。 - Webpack—— 解析
import建依赖图、 让 CSS 和图片也能被 import、 tree shaking、代码分割、 开发时提供 dev server 和热更新。
顺序:Webpack 遇到 .jsx时调用 babel-loader,Babel 是 Webpack 流水线上的一个环节。
会追问:「现在还用它们吗?」—— 这题答得出现状才显得在跟进: 新项目多用 Vite(开发用原生 ESM + esbuild, 生产用 Rollup),Babel 常被 esbuild / SWC 取代(快一个量级)。Webpack 仍在大量存量项目和 需要复杂定制的场景里。
我们这门课的 React 源项目用的就是 Vite —— 所以node_modules 里根本没有 webpack。
The split in one line: Babel translates (JSX and new syntax → JS the browser understands); Webpack bundles (a pile of modules and assets become the few files you ship).
- Babel —
@babel/preset-reacthandles JSX,@babel/preset-envdown-levels ES2020+ for your target browsers. It only transforms syntax; new APIs (Promise,Array.flat) still need a polyfill. Drawing that line scores points. - Webpack — reads your
imports to build a dependency graph, lets you import CSS and images too, does tree shaking and code splitting, and gives you a dev server with hot reload while you work.
The order: when Webpack hits a .jsx file it calls babel-loader, so Babel is one stage of the Webpack pipeline.
Follow-up: “Are they still used?” — knowing the current state is what shows you keep up: new projects mostly reach for Vite (native ESM plus esbuild in development, Rollup for production), and Babel is often replaced by esbuild or SWC — an order of magnitude faster. Webpack is still everywhere in existing codebases and wherever heavy customisation is needed.
The React source project in this course uses Vite — which is why there is no webpack in its node_modules at all.
换一道题也能用Works on other problems too
考试不会原题重考。真正能带走的是「看到这种信号 → 伸手去拿这个解法」。The exam will not reuse the same question. What you take away is the reflex: see this signal, reach for that solution.
- SPA 的代价是首屏慢、SEO 差、路由自己管、监听器不会自动清。What a SPA costs you: a slow first paint, weak SEO, routing you have to manage yourself, and listeners that are never cleaned up for you.
- React 三个卖点:声明式、组件化、单向数据流;缺点是选型成本和手动性能优化。Three things React sells you: a declarative style, components, and one-way data flow. The downsides are picking your own libraries and tuning performance by hand.
- JSX 编译成 createElement(17 后是 _jsx);{} 里只能放表达式;默认转义所以防 XSS。JSX compiles into createElement, or _jsx since React 17; only an expression can go inside {}; text is escaped by default, which blocks XSS.
- 虚拟 DOM 快在批量和最小化,但它是可维护性与性能的折中,不是性能银弹。The virtual DOM is fast because it batches and keeps real DOM work small, but it is a trade between maintainability and speed, not a guaranteed win.
- diff 三规则:只比同层、类型不同整棵重建、同层用 key 认身份。Three rules for diffing: compare only within the same level, rebuild the whole subtree when the type changes, and use key to identify siblings at the same level.
- reconciliation 是完整流程,Fiber 把它拆成可中断的 render 和不可中断的 commit。Reconciliation is the whole process; Fiber splits it into a render phase that can be interrupted and a commit phase that cannot.
- Babel 只转语法(新 API 靠 polyfill),Webpack 管打包;Babel 是 Webpack 流水线的一环。Babel only converts syntax, so a new API still needs a polyfill; Webpack does the bundling, and Babel is one step in the Webpack pipeline.