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

How can I make use of Error Boundaries in functional React components?

Câu trả lời

Error boundaries are a React feature that allows developers to catch JavaScript errors anywhere in their component tree, log those errors, and display a fallback UI instead of the component tree that crashed. However, it's important to note that error boundaries can only be directly implemented using class components in React, as they rely on lifecycle methods like componentDidCatch() or getDerivedStateFromError() which are not available in functional components[2][4][5][7][11][14].

Using Error Boundaries in Functional Components

Although functional components cannot directly implement error boundaries due to the absence of lifecycle methods, there are workarounds that allow you to use error boundaries within functional components:

  1. Wrapping Functional Components with Class Components:
    You can create a class component that serves as an error boundary and then wrap your functional components with this class. This class component would implement the necessary lifecycle methods to catch errors in the components it wraps[2][4].

    class ErrorBoundary extends React.Component {
        constructor(props) {
            super(props);
            this.state = { hasError: false };
        }
    
        static getDerivedStateFromError(error) {
            return { hasError: true };
        }
    
        componentDidCatch(error, errorInfo) {
            console.log(error, errorInfo);
        }
    
        render() {
            if (this.state.hasError) {
                return <h1>Something went wrong.</h1>;
            }
            return this.props.children;
        }
    }
    
    // Usage
    function MyFunctionalComponent() {
        return <div>My Functional Component</div>;
    }
    
    export default function App() {
        return (
            <ErrorBoundary>
                <MyFunctionalComponent />
            </ErrorBoundary>
        );
    }
  2. Using Higher-Order Components (HOC):
    You can use a higher-order component that wraps a functional component to provide it with error boundary capabilities. Libraries like react-error-boundary offer a convenient way to implement this pattern[3][6][9].

    import { withErrorBoundary } from 'react-error-boundary';
    import React from 'react';
    
    function MyComponent() {
        return <div>My Component</div>;
    }
    
    function ErrorFallback({error...
middle

middle

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

junior

What are Controlled components in ReactJS?

junior

What is the purpose of callback function as an argument of setState ?

senior

When is it important to pass props to super() , and why?

Bình luận

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

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