page.tsx
Overview
page.tsx is a React client component that demonstrates the integration of React's Suspense for data fetching with the popular SWR (stale-while-revalidate) hook library. The file provides a minimal example of conditional data fetching based on a toggle state, showcasing how to handle asynchronous data with suspense and fallback UI states.
Key functionalities:
Uses
useReducerto manage a boolean toggle state.Conditionally fetches data using SWR when the toggle is enabled.
Simulates a network request with a delay.
Suspends rendering of a child component (
Section) while data is loading.Displays fallback content during suspense.
This file is primarily meant as an example or template for implementing suspense-based data fetching in a React client component with SWR.
Detailed Explanation
Imports
Suspensefrom React: Allows components to "wait" for asynchronous operations and display a fallback UI.useReducerfrom React: Manages component state with a reducer pattern.useSWRfromswr: A React hook for data fetching with caching, revalidation, and more.
fetcher function
const fetcher = async (key: string) => {
// Add a small delay to simulate network request
await new Promise(resolve => setTimeout(resolve, 100))
return 'SWR'
}
Purpose: Simulates a data fetching function that SWR uses to fetch data.
Parameters:
key(string): The key identifying the data to fetch (not used in this simplified example).
Returns: A Promise that resolves to the string
'SWR'after a 100ms delay.Usage: Passed as the fetcher function to SWR to simulate network latency.
Section component
const Section = ({ trigger }: { trigger: boolean }) => {
const { data } = useSWR(trigger ? 'test-key' : undefined, fetcher, {
suspense: true
})
return <div>{data || 'empty'}</div>
}
Type: React functional component.
Props:
trigger(boolean) — Controls whether to run the data fetch or not.
Behavior:
Uses SWR with suspense mode enabled to fetch data only when
triggeristrue.When
triggeris false, SWR key isundefined, so no fetch occurs.While fetching, Suspense will show fallback UI.
Upon success, renders the fetched data.
Returns: A
<div>containing either the fetched data or'empty'if no data is fetched.Usage example:
<Section trigger={true} />
Default export: Page component
export default function Page() {
const [trigger, toggle] = useReducer(x => !x, false)
return (
<div>
<button onClick={toggle}>toggle</button>
<Suspense fallback={<div>fallback</div>}>
<Section trigger={trigger} />
</Suspense>
</div>
)
}
Type: React functional component, default export (likely the page component).
State:
trigger(boolean) — managed byuseReducertoggling betweentrueandfalse.
Behavior:
Renders a button that toggles the
triggerstate.Wraps the
Sectioncomponent in aSuspensecomponent with a fallback UI.When
triggeris toggledtrue,Sectionfetches data and suspends rendering until data arrives.When
triggerisfalse,Sectionrenders'empty'immediately.
Returns: A
<div>containing a toggle button and the suspense-enabledSection.
Implementation Details and Algorithms
Data Fetching with SWR + Suspense:
SWR is configured with
suspense: true. This means it will throw a Promise while loading, which React Suspense catches to show a fallback UI.The fetcher simulates a network delay with
setTimeoutwrapped in a Promise.Conditional fetching is controlled by passing either a valid key (
'test-key') orundefinedtouseSWR. Passingundefineddisables the fetch.
State Management:
useReduceris used for toggling a boolean state. The reducer function simply negates the current state.
User Interaction:
Clicking the "toggle" button flips the
triggerstate, triggering data re-fetch or clearing it.
Interaction with Other Parts of the System
This file acts as a self-contained component/page responsible for demonstrating client-side data fetching with suspense.
It depends on the
swrlibrary for data fetching logic.It relies on React 18+ Suspense support for data fetching.
Can be integrated into a larger React or Next.js application as a page or component.
The simulated fetcher can be replaced with real API calls, making this a good scaffold for real data-fetching pages.
Usage Example
import Page from './page'
function App() {
return <Page />
}
On clicking the "toggle" button, the component will either fetch data (showing fallback during load) or clear data and show 'empty'.
Mermaid Diagram
componentDiagram
component Page {
+trigger: boolean (state)
+toggle(): void
}
component Section {
+trigger: boolean (prop)
+data: string | undefined
}
component Suspense {
+fallback: ReactNode
}
Page --> Suspense : wraps
Suspense --> Section : wraps
Section --> fetcher : uses SWR to fetch data
Summary
page.tsx is a concise React client component illustrating suspense-enabled data fetching with SWR, controlled by a toggle state. It uses simulated network latency to demonstrate Suspense's fallback rendering and conditional data fetching. This file can serve as a template for building more complex data-driven pages with React Suspense and SWR.