Fix “Cannot perform a React state update on an unmounted component” warning

  • You have an asynchronous request to a backend API, you click a button that triggers the API, but you were not patient enough to wait for the response and navigate to a different route.
  • You have an event listener, but you fail to clean it up when the component unmounts
  • You have some setTimeout or setInterval that gets called after a component has unmounted, and it calls some setState operation.
  • Dispatch action only when the component is mounted

Generally, useEffect is handy in most of the scenarios for performance reasons. We don’t want to block browser paints with our callback code. But, if your code performs some manipulations with the DOM directly, then prefer useLayoutEffect in such cases.

  • We can prevent the API request from being processed using JavaScript’s AbortController API. Here is a modified version of useFetch with AbortController API.
  1. Create an instance of AbortController
  2. Pass the signal property of the controller to the fetch function
  3. Call controller.abort on component unmount. This cancels the request in flight. But, if the promise has been resolved and if you reach line number 28 before calling controller.abort, then line number 15 does not have any effect.
const controller = new AbortController();
const { signal } = controller;

fetch(url1, { signal });
fetch(url2, { signal });

controller.abort(); -> This aborts both the fetch calls with one signal




Fullstack developer at Unite

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

Recommended from Medium

Day 16: Become a self-taught blockchain developer with zero knowledge in 365 days

Let’s Loop through Arrays

Why do we need a Middleware in Redux?

Do you really know React? #InterviewQuestions

Angular vs React vs Vue : Which to choose for your career as a UI developer

Using in-memory-db With NestJS

A Quick Essential Guide to Getting Started With Redux

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
Aishwaryalakshmi Panneerselvam

Aishwaryalakshmi Panneerselvam

Fullstack developer at Unite

More from Medium

Setup React Relay in an Nx Mono Repo


SVG as Text for React apps

Elegantly type React’s useReducer and Context API with discriminated union of Typescript