On-Demand React Component Loading with Loading Placeholder
Utilize React's lazy and Suspense to only load components when needed, with a loading UI feedback.
import React, { Suspense, lazy } from 'react';
// Lazy load the component, only load it when it's needed
const LazyComponent = lazy(() => import('./LazyComponent'));
function App() {
return (
<div>
<Suspense fallback={<div>Loading...</div>}>
<LazyComponent />
</Suspense>
</div>
);
}
export default App;
This piece of code demonstrates the use of React's lazy and Suspense. The LazyComponent is imported using the lazy function, which means it will not be loaded until it's required. The Suspense component wraps the lazy component and provides a fallback UI, in this case, a simple 'Loading...' message, to be displayed while the lazy component is being loaded.