미디엄을 보다가 반갑게도 리액트에 관한 글을 보게 됐다.
React Error Boundaries Explained
: Error Boundaries는 하위 컴포넌트 트리에서 자바스크립트 에러를 찾아 기록하고, 에러난 컴포넌트 대신에 fallbackUI를 보여주는 리액트 컴포넌트다.
왜 필요한걸까?
UI 일부에 존재하는 자바스크립트 에러 때문에 전체 어플리케이션이 중단되버리는 것을 막기 위해서다. 말하자면 사용자 경험을 위해서라는 건데.. 그 외에 앞으로의 동작에서 문제를 일으킬 여지도 있다고 한다.
왜 일부 에러 때문에 전체를 중단시켜버리지?
리액트 팀에서는 잘못된 정보를 사용자에게 보여주는 것보다 아무것도 보여주지 않는 것이 낫다고 판단했기 때문
class ErrorBoundary extends React.Component {
constructor(props) {
super(props);
this.state = { hasError: false };
}
static getDerivedStateFromError(error) {
// Update state so the next render will show the fallback UI.
return { hasError: true };
}
componentDidCatch(error, errorInfo) {
// You can also log the error to an error reporting service
logErrorToMyService(error, errorInfo);
}
render() {
if (this.state.hasError) {
// You can render any custom fallback UI
return <h1>Something went wrong.</h1>;
}
return this.props.children;
}
}
<ErrorBoundary>
<MyWidget />
</ErrorBoundary>