・Error Boundary is used for caching JavaScript errors in the child component tree. This displays a fallback UI instead of crashing the entire app.
import { useState } from "react";
import { ErrorBoundary } from "react-error-boundary";
function FallbackErrorComponent({ error, resetErrorBoundary }) {
return (
<div>
<p>{error.message}</p>
<button onClick={resetErrorBoundary}>Reset</button>
</div>
);
}
function ErrorComponent({ isError, setIsError}) {
if (isError) {
throw new Error("Error!");
}
return (
<div>
<p>This component works fine until you click the button</p>
<button onClick={() => setIsError(true)}>Error Button</button>
</div>
);
}
function App() {
const [isError, setIsError] = useState(false);
return (
<div>
<ErrorBoundary
FallbackComponent={FallbackErrorComponent}
onReset={() => setIsError(false)}
>
<ErrorComponent
isError={isError}
setIsError={setIsError}
/>
</ErrorBoundary>
</div>
);
}
export default App;
Top comments (0)