How do you handle errors in a React component?
33. What is the purpose of the componentDidCatch() method?
35. What are some ways to optimize the performance of React components?
In React, you can handle errors in a component using the componentDidCatch()
lifecycle method.
Javascript
// ErrorBoundary component to catch errors class ErrorBoundary extends Component { constructor(props) { super (props); this .state = { hasError: false }; } componentDidCatch(error, info) { console.error( 'Error caught by error boundary:' , error, info); this .setState({ hasError: true }); } render() { if ( this .state.hasError) { return <p>Something went wrong. Please try again later.</p>; } return this .props.children; } } // App component wrapping MyComponent with ErrorBoundary const App = () => { return ( <ErrorBoundary> <MyComponent /> </ErrorBoundary> ); }; export default App; |
Top React Components Interview Questions & Answers
React Component is the building blocks of the React application. It is the core concept that everyone must know while working on React. In this tutorial, we will see the top React Components questions that can be asked in the interview.
Let’s discuss some common questions that you should prepare for the interviews. These questions will be helpful in clearing the interviews, especially for the frontend development or full stack development role.