Avoiding race conditions and memory leaks in React useEffect

By Wisdom Geek - 2021-02-08

Description

When making API calls, it is possible to run into race conditions using useEffect. To fix it, we need to cancel all asynchronous tasks in the cleanup function.

Summary

  • We have specified an empty array as a dependency to the useEffect React hook.
  • AbortController is not supported in IE though.
  • useEffect cleanup with AbortController Though the previous approach works, it is not the best way to handle race conditions.
  • From our previous post about how to cancel an HTTP fetch request, we know about the AbortController API that was added to the DOM standard.

 

Topics

  1. Frontend (0.45)
  2. Backend (0.13)
  3. Database (0.06)

Similar Articles

How to Fetch Data in React: Cheat Sheet + Examples

By freeCodeCamp.org - 2021-02-12

There are many ways to fetch data from an external API in React. But which one should you be using for your applications in 2021? In this tutorial, we will be reviewing five of the most commonly used ...

sudheerj/reactjs-interview-questions

By GitHub - 2021-01-12

List of top 500 ReactJS Interview Questions & Answers....Coding exercise questions are coming soon!! - sudheerj/reactjs-interview-questions

8 Awesome React Hooks

By DEV Community - 2020-12-30

React.js is currently the most popular JavaScript library for front end developers. Invented by Faceb... Tagged with react, javascript, webdev, beginners.

A Thoughtful Way To Use React’s useRef() Hook

By Smashing Magazine - 2020-11-19

In a React component, useState and useReducer can cause your component to re-render each time there is a call to the update functions. In this article, you will find out how to use the useRef() hook t ...