Notice
Recent Posts
Recent Comments
Link
«   2025/05   »
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31
Archives
Today
Total
관리 메뉴

new_bird-hyun

React에서 Suspense와 Error Boundary로 안정적인 비동기 처리 본문

코딩 공부

React에서 Suspense와 Error Boundary로 안정적인 비동기 처리

새혀니 2025. 1. 4. 18:23

// ErrorBoundary.js

 

import React, { Component } from 'react';

export default class ErrorBoundary extends Component {
  constructor(props) {
    super(props);
    this.state = { hasError: false };
  }

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

  componentDidCatch(error, errorInfo) {
    console.error('ErrorBoundary caught an error:', error, errorInfo);
  }

  render() {
    if (this.state.hasError) {
      return <h1>문제가 발생했습니다. 다시 시도해주세요.</h1>;
    }
    return this.props.children;
  }
}

 

 

 

// SuspenseExample.js

import React, { Suspense } from 'react';

const fetchData = () =>
  new Promise((resolve) =>
    setTimeout(() => resolve('비동기 데이터 로드 완료!'), 2000)
  );

const AsyncComponent = React.lazy(() =>
  fetchData().then((data) => ({
    default: () => <p>{data}</p>,
  }))
);

export default function SuspenseExample() {
  return (
    <div>
      <h1>React Suspense 예제</h1>
      <ErrorBoundary>
        <Suspense fallback={<p>Loading...</p>}>
          <AsyncComponent />
        </Suspense>
      </ErrorBoundary>
    </div>
  );
}