Skip to content

Instantly share code, notes, and snippets.

@sangdth
Created February 25, 2023 08:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sangdth/aa856c7aa9981a1e93a39f7d452a19ec to your computer and use it in GitHub Desktop.
Save sangdth/aa856c7aa9981a1e93a39f7d452a19ec to your computer and use it in GitHub Desktop.
Implementation of an error boundary in React functional component
import { useState, useEffect } from 'react';
function ErrorBoundary({ fallback, children }) {
const [error, setError] = useState(null);
useEffect(() => {
if (error) {
// log the error or send it to a server
console.error(error);
}
}, [error]);
function resetError() {
setError(null);
}
function handleComponentError(error) {
setError(error);
}
if (error) {
// render the fallback UI
return React.cloneElement(fallback, { resetError });
}
return (
// render the children normally
<React.Fragment>
{React.Children.map(children, child =>
React.cloneElement(child, {
onError: handleComponentError,
})
)}
</React.Fragment>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment