<Suspense> and Lazy in React Projects:
React Suspense -
- What is React Suspense?
The suspense component is required to wrap lazy components in programming. It takes a fallback property that accepts the react elements to render while the lazy component is being loaded.With react suspense, components may pause rendering while they wait for an asynchronous process to finish, like separating code or retrieving data.
- How Does React Suspense Work?
React Suspense simplifies handling asynchronous operations by rendering a fallback UI while waiting for data, and smoothly transitioning to the real content once the data is available. This automation makes it significantly easier for developers to manage asynchronous actions without complex coding.
- Only Suspense-enabled data sources will activate the Suspense component.
They include:
- Data fetching with Suspense-enabled frameworks like Relay and Next.js
- Lazy-loading component code with
lazy
- Reading the value of a Promise with
use
- Example :
Output:
React Lazy -
- What is React Lazy {React.lazy()}?
Lazy evaluation is a strategy in programming language theory that delays the evaluation of an expression until its value is needed. It also avoids repeated evaluations by using sharing.
- Why is Lazy Loading (& Suspense) Important?
- Bundling:
- Aligns code components and puts them in a single JavaScript chunk.
- As the application grows, the bundle size becomes very cumbersome.
- Code Splitting:
- Allows the bundle to be split into smaller chunks.
- The most important chunk can be loaded first. Secondary chunks can be lazily loaded
- Consideration for Users:
- Developers should consider users with mobile internet data and slow internet connections.
- Developers should be able to control the user experience during the loading period.
- Example:
Output:
Suspense and Lazy:
Suspense is ideal for showing a backup while waiting for something to load. The main use cases are waiting for data from an API after the initial page load and lazy loading other React components.