Can you provide an example of how to implement a functional component error boundary?

Question

Grade: Education Subject: Support
Can you provide an example of how to implement a functional component error boundary?
Asked by:
85 Viewed 85 Answers

Answer (85)

Best Answer
(681)
```javascript import React, { useState } from 'react'; function MyComponent() { // Example component const [error, setError] = useState(null); const handleButtonClick = () => { try { // Simulate an error - could be a network request, data validation, etc. throw new Error('Something went wrong!'); } catch (err) { setError(err.message); } }; return (
{error &&

Error: {error}

}
); } export default MyComponent; ``` This example demonstrates how to catch errors within a functional component and update the state to display an error message.