0
# Dynamic Component Loading
1
2
Core functionality for creating loadable components that dynamically load modules before rendering. This enables code splitting at the component level, reducing initial bundle sizes and improving application performance.
3
4
## Capabilities
5
6
### Loadable Function
7
8
Creates a loadable component that handles dynamic imports with loading states, error handling, and customizable rendering.
9
10
```javascript { .api }
11
/**
12
* Creates a higher-order component for dynamic component loading
13
* @param options - Configuration object for the loadable component
14
* @returns LoadableComponent class
15
*/
16
function Loadable(options: LoadableOptions): LoadableComponent;
17
18
interface LoadableOptions {
19
/** Function that returns a promise resolving to the module */
20
loader: () => Promise<any>;
21
/** Component to render during loading/error states */
22
loading: LoadingComponent;
23
/** Delay in milliseconds before showing loading component (default: 200) */
24
delay?: number;
25
/** Timeout in milliseconds before showing timeout state (default: null) */
26
timeout?: number;
27
/** Custom render function for the loaded module */
28
render?: (loaded: any, props: any) => React.ReactElement;
29
/** Function returning webpack module IDs for SSR */
30
webpack?: () => number[];
31
/** Array of module paths for SSR */
32
modules?: string[];
33
}
34
```
35
36
**Usage Examples:**
37
38
```javascript
39
import React from 'react';
40
import Loadable from 'react-loadable';
41
42
// Simple loadable component
43
const LoadableButton = Loadable({
44
loader: () => import('./Button'),
45
loading: () => <div>Loading button...</div>,
46
});
47
48
// Advanced configuration with error handling
49
const LoadableChart = Loadable({
50
loader: () => import('./Chart'),
51
loading: LoadingComponent,
52
delay: 300,
53
timeout: 10000,
54
render(loaded, props) {
55
const Chart = loaded.default;
56
return <Chart {...props} />;
57
},
58
});
59
60
function LoadingComponent(props) {
61
if (props.error) {
62
return <div>Error! <button onClick={props.retry}>Retry</button></div>;
63
} else if (props.timedOut) {
64
return <div>Taking a long time... <button onClick={props.retry}>Retry</button></div>;
65
} else if (props.pastDelay) {
66
return <div>Loading...</div>;
67
} else {
68
return null;
69
}
70
}
71
```
72
73
### LoadableComponent
74
75
The component returned by `Loadable()`, which renders the loading component while the module loads and then renders the loaded component.
76
77
```javascript { .api }
78
/**
79
* Component created by Loadable function
80
*/
81
interface LoadableComponent extends React.Component {
82
/** Static method to preload the component */
83
static preload(): Promise<any>;
84
}
85
```
86
87
**Usage Examples:**
88
89
```javascript
90
// Preload component on user interaction
91
const LoadableModal = Loadable({
92
loader: () => import('./Modal'),
93
loading: Loading,
94
});
95
96
function App() {
97
const [showModal, setShowModal] = useState(false);
98
99
const handleMouseOver = () => {
100
// Preload component when user hovers
101
LoadableModal.preload();
102
};
103
104
const handleClick = () => {
105
setShowModal(true);
106
};
107
108
return (
109
<div>
110
<button onMouseOver={handleMouseOver} onClick={handleClick}>
111
Show Modal
112
</button>
113
{showModal && <LoadableModal onClose={() => setShowModal(false)} />}
114
</div>
115
);
116
}
117
```
118
119
### Loading Component Interface
120
121
The loading component receives props that describe the current loading state and provide error recovery functionality.
122
123
```javascript { .api }
124
/**
125
* Props passed to the loading component
126
*/
127
interface LoadingComponentProps {
128
/** Whether the module is currently loading */
129
isLoading: boolean;
130
/** Whether the delay threshold has been exceeded */
131
pastDelay: boolean;
132
/** Whether the timeout threshold has been exceeded */
133
timedOut: boolean;
134
/** Error object if loading failed, null otherwise */
135
error: Error | null;
136
/** Function to retry loading after an error */
137
retry: () => void;
138
}
139
140
/**
141
* Component type for loading states
142
*/
143
type LoadingComponent = React.ComponentType<LoadingComponentProps>;
144
```
145
146
**Usage Examples:**
147
148
```javascript
149
// Comprehensive loading component
150
function LoadingComponent(props) {
151
if (props.error) {
152
return (
153
<div className="error">
154
<p>Failed to load component</p>
155
<button onClick={props.retry}>Try Again</button>
156
</div>
157
);
158
}
159
160
if (props.timedOut) {
161
return (
162
<div className="timeout">
163
<p>Taking longer than expected...</p>
164
<button onClick={props.retry}>Retry</button>
165
</div>
166
);
167
}
168
169
if (props.pastDelay) {
170
return <div className="loading">Loading...</div>;
171
}
172
173
return null; // Don't show anything initially
174
}
175
176
// Minimal loading component
177
const SimpleLoading = (props) =>
178
props.error ? <div>Error!</div> :
179
props.pastDelay ? <div>Loading...</div> : null;
180
```
181
182
### Custom Rendering
183
184
Customize how the loaded module is rendered using the `render` option.
185
186
```javascript { .api }
187
/**
188
* Custom render function type
189
* @param loaded - The resolved module from the loader
190
* @param props - Props passed to the LoadableComponent
191
* @returns React element to render
192
*/
193
type RenderFunction = (loaded: any, props: any) => React.ReactElement;
194
```
195
196
**Usage Examples:**
197
198
```javascript
199
// Render specific export from module
200
const LoadableIcon = Loadable({
201
loader: () => import('./icons'),
202
loading: Loading,
203
render(loaded, props) {
204
const Icon = loaded[props.iconName];
205
return <Icon {...props} />;
206
},
207
});
208
209
// Add props transformation
210
const LoadableAPI = Loadable({
211
loader: () => import('./APIComponent'),
212
loading: Loading,
213
render(loaded, props) {
214
const APIComponent = loaded.default;
215
return <APIComponent {...props} apiKey={process.env.REACT_APP_API_KEY} />;
216
},
217
});
218
```
219
220
## Configuration Options
221
222
### Delay Configuration
223
224
Control when the loading component appears to avoid flash of loading content for fast-loading components.
225
226
```javascript
227
// Show loading immediately
228
const LoadableImmediate = Loadable({
229
loader: () => import('./Component'),
230
loading: Loading,
231
delay: 0,
232
});
233
234
// Wait 500ms before showing loading
235
const LoadableDelayed = Loadable({
236
loader: () => import('./Component'),
237
loading: Loading,
238
delay: 500,
239
});
240
```
241
242
### Timeout Configuration
243
244
Set a timeout for loading operations to handle slow network conditions.
245
246
```javascript
247
// 5 second timeout
248
const LoadableWithTimeout = Loadable({
249
loader: () => import('./Component'),
250
loading: Loading,
251
timeout: 5000,
252
});
253
```
254
255
### Server-Side Rendering Options
256
257
Configure webpack and modules options for server-side rendering support.
258
259
```javascript
260
// Manual configuration (usually automated by Babel plugin)
261
const LoadableSSR = Loadable({
262
loader: () => import('./Component'),
263
loading: Loading,
264
webpack: () => [require.resolveWeak('./Component')],
265
modules: ['./Component'],
266
});
267
```