How To Create A NetworkErrorBoundary Component With React

The Component

import { useState, useEffect } from ‘react’;export const NetworkErrorBoundary = ({ children, fallback }) => {
const [hasError, setHasError] = useState(false);
useEffect(() => {
if (!window) return;
const handler = (event) => {
window.addEventListener(‘unhandledrejection’, handler); return () => {
window.removeEventListener(‘unhandledrejection’, handler);
}, []);
return hasError ? fallback : children;


<NetworkErrorBoundary fallback={<p>An error has occured, please reload the page.</p>}>
<App />
function App() {
useEffect(() => {
setTimeout(() => {
}, 2000);
}, []);
return (

The Result





Frontend Developer at AWS Berlin, Germany

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

React App | Next js Server side rendering Framework

Redux From Scratch (Chapter 4 | Async Practice With Twitch API)

Why is True Modular Encapsulation So Important in Large-Scale GraphQL Projects?

How to choose between Angular and React for your next application

The Advantage of Headless Components

Send Messages from Node.js App with Alibaba Cloud SMS

Functional Programming with JavaScript

Building a color picker using plain JS and CSS

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Nikita Mingaleev

Nikita Mingaleev

Frontend Developer at AWS Berlin, Germany

More from Medium

React State Management: Hook

React Hooks —  useReducer() — A Detailed Look

Introduction of React Hooks

What’s New in React 18?