page.tsx

Overview

page.tsx is a React component file designed to benchmark rendering performance differences between two approaches of rendering a large number of components (10,000 in this case). It contrasts:

The file exports a main component, PerformancePage, which allows the user to toggle between rendering the cheap or expensive component sets. This enables developers to observe and compare the rendering cost of using hooks like SWR at scale.

Components and Functions


useData

const useData = () => {
  return useSWR('1', async (url: string) => {
    return 1
  })
}
const { data } = useData();
console.log(data); // 1

HookUser

const HookUser = () => {
  const { data } = useData();
  return <div>{data}</div>;
}
<HookUser />  // Renders: <div>1</div>

CheapComponent

const CheapComponent = () => {
  const cheapComponents = Array.from({ length: elementCount }, (_, i) => (
    <div key={i}>{i}</div>
  ));
  return (
    <div>
      <h2>Cheap Component</h2>
      {cheapComponents}
    </div>
  )
}
<CheapComponent />

ExpensiveComponent

const ExpensiveComponent = () => {
  const hookComponents = Array.from({ length: elementCount }, (_, i) => (
    <HookUser key={i} />
  ));
  return (
    <div>
      <h2>Expensive Component</h2>
      {hookComponents}
    </div>
  )
}
<ExpensiveComponent />

PerformancePage (default export)

export default function PerformancePage() {
  const [renderExpensive, setRenderExpensive] = useState(false);
  return (
    <div>
      <h1>Performance Page</h1>
      <label>
        <input
          type="checkbox"
          checked={renderExpensive}
          onChange={e => setRenderExpensive(e.target.checked)}
        />
        Render with swr
      </label>
      {!renderExpensive ? <CheapComponent /> : <ExpensiveComponent />}
    </div>
  )
}
<PerformancePage />

Important Implementation Details / Algorithms

Interaction with Other Parts of the System


Visual Diagram

componentDiagram
    PerformancePage --|> CheapComponent : renders (if unchecked)
    PerformancePage --|> ExpensiveComponent : renders (if checked)
    ExpensiveComponent *-- HookUser : renders 10,000 instances
    HookUser *-- useData : uses SWR hook
    useData ..> useSWR : calls

Diagram Explanation:


Summary

page.tsx provides an interactive performance testing page that contrasts rendering many simple elements versus many hook-based components. It leverages React state, SWR caching, and bulk rendering to highlight the cost differences in UI rendering strategies. This file is useful for developers to empirically evaluate rendering overhead in React applications using hooks and large component trees.