Sobes.tech
Middle

Tell me about Suspense and code splitting in React.

sobes.tech AI

Answer from AI

In React, Suspense is a mechanism for managing the loading state of components or data, allowing you to display a fallback UI (such as a spinner) while the main content loads. It is closely related to code splitting, where the application is divided into chunks that are loaded as needed, reducing the initial bundle size and speeding up load times.

React.lazy allows for dynamic import of components, and Suspense wraps these components, showing fallback UI during loading.

Example:

import React, { Suspense } from 'react';
const LazyComponent = React.lazy(() => import('./LazyComponent'));

function App() {
  return (
    <Suspense fallback={<div>Loading...</div>}>
      <LazyComponent />
    </Suspense>
  );
}

Thus, Suspense simplifies working with asynchronous components and improves UX when splitting code.

Tell me about Suspense and code splitting in React… - sobes.tech