Loading...
Loading...
Compare original and translation side by side
import { createRoot } from 'react-dom/client'
import { useEffect, useState } from 'react'
function Clock() {
const [time, setTime] = useState(new Date())
useEffect(() => {
const id = setInterval(() => setTime(new Date()), 1000)
return () => clearInterval(id)
}, [])
return (
<div>
<h1>Hello, world!</h1>
<h2>It is {time.toLocaleTimeString()}.</h2>
</div>
)
}
createRoot(document.getElementById('root')!).render(<Clock />)<div id="root"></div><div>import { createRoot } from 'react-dom/client'
import { useEffect, useState } from 'react'
function Clock() {
const [time, setTime] = useState(new Date())
useEffect(() => {
const id = setInterval(() => setTime(new Date()), 1000)
return () => clearInterval(id)
}, [])
return (
<div>
<h1>Hello, world!</h1>
<h2>It is {time.toLocaleTimeString()}.</h2>
</div>
)
}
createRoot(document.getElementById('root')!).render(<Clock />)<div id="root"></div><div>Note (React 18+): Reevaluate Pure CSR for Initial LoadsWhile CSR yields a rich interactive experience after load, it has well-known drawbacks for first-page load performance and SEO. Today's best practice is to avoid pure-CSR for content-rich or public-facing pages. Instead, use hybrid approaches (SSR/SSG plus hydration) for the initial render. Frameworks like Next.js now default to pre-rendering pages on the server (or at build time) and then hydrating on the client.Server-rendering HTML can drastically improve FCP and make content indexable for search engines. React 18's improvements (automatic batching, Suspense, streaming) make SSR + hydration very performant. React 18 also introduced Progressive Hydration and Selective Hydration which mitigate the traditional TTI gap—React can hydrate parts of the UI as their scripts arrive or as the user interacts.Conclusion: Pure CSR (loading a big bundle and rendering everything on client) is generally discouraged for large apps. Use SSR/SSG for initial content and hydrate on the client. If you do use CSR (e.g., an internal dashboard where SEO doesn't matter), apply aggressive code-splitting and use React 18'swith lazy-loaded components to defer loading non-critical parts of the UI.<Suspense>
注意(React 18+):重新评估纯CSR在初始加载中的应用虽然CSR在加载后能提供丰富的交互体验,但它在首屏加载性能和SEO方面存在众所周知的缺点。如今的最佳实践是避免在内容丰富或面向公众的页面中使用纯CSR。相反,应使用混合方法(SSR/SSG加注水)进行初始渲染。Next.js等框架现在默认在服务器(或构建时)预渲染页面,然后在客户端进行注水。服务器渲染HTML可以显著提升FCP,并使内容可被搜索引擎索引。React 18的改进(自动批处理、Suspense、流式传输)使SSR + 注水的性能非常出色。React 18还引入了渐进式注水和选择性注水,缓解了传统的TTI差距——React可以在脚本到达或用户交互时为UI的部分内容进行注水。结论: 纯CSR(加载大体积包并在客户端渲染所有内容)通常不推荐用于大型应用。对初始内容使用SSR/SSG,然后在客户端进行注水。如果确实要使用CSR(例如SEO无关紧要的内部仪表板),请采用激进的代码分割,并结合React 18的和懒加载组件来延迟加载UI的非关键部分。<Suspense>
<head><link rel="preload" as="script" href="critical.js" />critical.js<head><link rel="preload" as="script" href="critical.js" />critical.js