React Suspense Vs Error Boundary? Complete Example Tutorial

Suspense vs Error Boundary

  • Suspense: Handles loading states for lazy-loaded components or data fetching.
  • Error Boundary: Catches runtime errors in component tree and displays fallback UI.

Suspense Example

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

const LazyComponent = lazy(() => import("./LazyComponent"));

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

export default App;

✅ Suspense shows fallback while the component is loading.


Error Boundary Example

import React from "react";

class ErrorBoundary extends React.Component {
  state = { hasError: false };

  static getDerivedStateFromError() {
    return { hasError: true };
  }

  render() {
    if (this.state.hasError) return <h2>Something went wrong.</h2>;
    return this.props.children;
  }
}

function Buggy() {
  throw new Error("Crash!");
}

function App() {
  return (
    <ErrorBoundary>
      <Buggy />
    </ErrorBoundary>
  );
}

✅ Prevents the app from crashing and shows fallback UI.


Key Differences

FeatureSuspenseError Boundary
PurposeHandles lazy-loading stateHandles runtime errors
FallbackLoading indicatorError UI
ScopeLazy componentsComponent subtree
UsageWith lazy & SuspenseClass components only

Conclusion

Use Suspense for loading states and Error Boundary for error handling, making React apps robust and user-friendly.


Citations

https://savanka.com/category/learn/react/
https://www.w3schools.com/REACT/DEFAULT.ASP

Leave a Comment

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *