Câu hỏi phỏng vấn Reactjs
Câu hỏi

What are Error Boundaries in ReactJS?

Câu trả lời

Error boundaries in ReactJS are components that catch JavaScript errors anywhere in their child component tree, log those errors, and display a fallback UI instead of the component tree that crashed. They act as a catch mechanism for unhandled errors in the component tree, allowing an application to continue running and providing a better user experience in the event of an error.

Error boundaries catch errors during rendering, in lifecycle methods, and in constructors of the whole tree below them. However, they do not catch errors for:

  • Event handlers (React doesn’t need error boundaries to recover from errors in event handlers)
  • Asynchronous code (e.g., setTimeout or requestAnimationFrame callbacks)
  • Server-side rendering
  • Errors thrown in the error boundary itself (rather than its children)

To define an error boundary, you create a class component that implements either or both of the lifecycle methods static getDerivedStateFromError() or componentDidCatch(). The getDerivedStateFromError() method is used to render a fallback UI after an error has been thrown, while componentDidCatch() is used to log error information.

Here's an example of an error boundary component:

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 <...
middle

middle

Gợi ý câu hỏi phỏng vấn

middle

Which lifecycle methods of class component is replaced by useEffect in functional component?

middle

Compare useState and useReducer implementations

junior

What are the advantages of using React?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào