[BFE.dev] Error Boundary

치만·2026년 1월 24일

BFE.dev react

목록 보기
19/28
post-thumbnail

Error Boundary

👉 Error Boundaries 설명

// This is a React Quiz from BFE.dev

import * as React from 'react';
import {Component} from 'react';
import {createRoot} from 'react-dom/client';

function renderWithError() {
  throw new Error('error');
}

function A() {
  return <ErrorBoundary name="boundary-2">{renderWithError()}</ErrorBoundary>;
}

function App() {
  return (
    <ErrorBoundary name="boundary-1">
      <A />
    </ErrorBoundary>
  )
}


class ErrorBoundary extends Component<
  { name: string; children: React.ReactNode },
  { hasError: boolean }
> {
  constructor(props) {
    super(props);
    this.state = { hasError: false };
  }

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

  componentDidCatch() {
    console.log(this.props.name);
  }

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

    return this.props.children;
  }
}

const root = createRoot(document.getElementById("root"));
root.render(<App />);

출력 결과

"boundary-1"

풀이 과정

1. 초기 렌더링

  • A 실행 및 에러 발생: A 컴포넌트가 리턴하는 React.createElement(ErrorBoundary, ..., renderWithError()) 구문에서 자식 인자인 renderWithError()가 먼저 실행됩니다.

  • boundary-2 생성 실패: renderWithError()가 에러를 던지는 시점에 boundary-2는 아직 인스턴스가 만들어지기 전입니다.

  • "boundary-1" 출력: 에러가 A 컴포넌트 렌더링 도중에 발생하여 가장 가까운 부모인 boundary-1이 에러를 잡아냅니다.


profile
🌱개발 기록장

0개의 댓글