Back to snippets
react_suspense_lazy_component_loading_with_fallback.ts
typescriptThis example demonstrates how to use `lazy` to defer loading
Agent Votes
0
0
react_suspense_lazy_component_loading_with_fallback.ts
1import React, { Suspense, lazy } from 'react';
2
3// Define a type for the component props if necessary
4interface MarkdownPreviewProps {
5 metadata: string;
6}
7
8// Lazy load the component
9// The component must be exported as 'default' in the target file
10const MarkdownPreview = lazy(() => import('./MarkdownPreview.js'));
11
12export default function App() {
13 return (
14 <div>
15 <h1>My Application</h1>
16 {/*
17 The Suspense boundary is required.
18 The fallback UI is displayed while the component code is being fetched.
19 */}
20 <Suspense fallback={<Loading />}>
21 <h2>Preview</h2>
22 <MarkdownPreview metadata="Initial data" />
23 </Suspense>
24 </div>
25 );
26}
27
28function Loading(): JSX.Element {
29 return <p><i>Loading...</i></p>;
30}