DEV Community

DIWAKARKASHYAP
DIWAKARKASHYAP

Posted on

Suspense in React ? Most Important component

Imagine you're at a restaurant. You've given your order to the waiter, and now you're waiting for your food to arrive. While you're waiting, you might be sipping on some water or chatting with your friends. You aren't just staring at the table doing nothing, right?

In the world of web apps, "Suspense" in React works somewhat like that waiting period. When your app needs to get some data (like your order from the kitchen), it might take some time. Instead of making users stare at a blank screen or a partially loaded page (an empty table), React allows you to show something else (like sipping water or chatting) in the meantime. This could be a loading spinner, a placeholder, or anything else to indicate that data is on the way.

Here's an example:

import React, { lazy, Suspense } from 'react';

// This line means "We want to load another part of our app, but it might take some time."
const OtherComponent = lazy(() => import('./OtherComponent'));

function MyComponent() {
  return (
    <div>
      {/* Here we're saying, "While we're waiting, show 'Loading...'." */}
      <Suspense fallback={<div>Loading...</div>}>
        {/* And here's the part of the app we're waiting for. */}
        <OtherComponent />
      </Suspense>
    </div>
  );
}

export default MyComponent;
Enter fullscreen mode Exit fullscreen mode

In this example, OtherComponent is like your food order, and the Loading... message is what you're doing while you wait. When OtherComponent finishes loading (the food arrives), React automatically swaps out the Loading... message with the OtherComponent (you stop waiting and start eating).

In short, Suspense in React helps keep your app interactive and user-friendly even while it's waiting for data or other resources. It's like having a good conversation while waiting for your meal at a restaurant!

Thank you for reading. I encourage you to follow me on Twitter where I regularly share content about JavaScript and React, as well as contribute to open-source projects. I am currently seeking a remote job or internship.

Twitter: https://twitter.com/Diwakar_766

GitHub: https://github.com/DIWAKARKASHYAP

Portfolio: https://diwakar-portfolio.vercel.app/

Top comments (0)