remote-data.tsx

Overview

remote-data.tsx is a React client-side component file that demonstrates the use of SWR (stale-while-revalidate) for fetching remote data asynchronously with React Suspense support. It showcases how to preload data before rendering a component that depends on it, improving the perceived performance and user experience.

The main functionality revolves around:

This file serves as a minimal example of integrating SWR's data fetching with React Suspense and preloading capabilities.


Detailed Explanation

Dependencies and Imports

Constants and Utility Functions

fetcher

const fetcher = ([key, delay]: [key: string, delay: number]) =>
  new Promise<string>(r => {
    setTimeout(r, delay, key)
  })

key

const key = ['suspense-after-preload', 300] as const

Hook: useRemoteData

const useRemoteData = () =>
  useSWR(key, fetcher, {
    suspense: true
  })

Component: Demo

const Demo = () => {
  const { data } = useRemoteData()
  return <div>{data}</div>
}

Component: Comp

function Comp() {
  const [show, toggle] = useState(false)

  return (
    <div className="App">
      <button
        onClick={async () => {
          preload(key, fetcher)
          toggle(!show)
        }}
      >
        preload
      </button>
      {show ? (
        <Suspense fallback={<div>loading</div>}>
          <Demo />
        </Suspense>
      ) : null}
    </div>
  )
}

Important Implementation Details


Interaction with Other System Parts


Usage Example

To use this component in an application:

import Comp from './remote-data'

function App() {
  return (
    <div>
      <h1>Remote Data Demo</h1>
      <Comp />
    </div>
  )
}

Mermaid Diagram: Component Interaction and Flow

flowchart TD
    A[Comp Component] -->|Button Click| B[preload(key, fetcher)]
    B --> C[Cache Data in SWR]
    A -->|Toggles show state| D{show ?}
    D -->|true| E[Suspense Boundary]
    E --> F[Demo Component]
    F -->|Calls| G[useRemoteData Hook]
    G -->|Uses| H[useSWR with Suspense]
    H -->|Fetches with| I[fetcher(key, delay)]
    I -->|Returns Promise resolving after delay| C
    E -->|fallback| J[Loading UI]

Summary

remote-data.tsx is a concise demonstration of integrating SWR's data fetching with React Suspense and preloading. It features:

This pattern is useful for improving UX in React applications that deal with asynchronous data by minimizing loading flickers and enabling seamless data transitions.