Now that
The useEffect
hook is among the most popular, as it can replace componentDidMount
, componentDidUpdate
, and componentWillUnmount
.
Most of the initialization, updates, and cleanup logic that a component may need can be put inside of useEffect
.
On a recent project, I encountered a scenario where useEffect
acted on HTTP requests that I was no longer interested in.
Conceptually, the UI was like this:
On first load, fetch the list of fruits and render a <button>
for each one.
Click a <button>
to fetch that fruit’s details.
But clicking multiple fruits in a row reveals a weird behavior. Run the sample application and try it out.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta name="theme-color" content="#000000"> <!-- manifest.json provides metadata used when your web app is added to the homescreen on Android. See https://developers.google.com/web/fundamentals/engage-and-retain/web-app-manifest/ --> <link rel="manifest" href="%PUBLIC_URL%/manifest.json"> <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico"> <!-- Notice the use of %PUBLIC_URL% in the tags above. It will be replaced with the URL of the `public` folder during the build. Only files inside the `public` folder can be referenced from the HTML. Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will work correctly both with client-side routing and a non-root public URL. Learn how to configure a non-root public URL by running `npm run build`. --> <title>React App</title> </head> <body> <noscript> You need to enable JavaScript to run this app. </noscript> <div id="root"></div> <!-- This HTML file is a template. If you open it directly in the browser, you will see an empty page. You can add webfonts, meta tags, or analytics to this file. The build step will place the bundled scripts into the <body> tag. To begin the development, run `npm start` or `yarn start`. To create a production bundle, use `npm run build` or `yarn build`. --> </body> </html>
Did you catch it? Here’s a GIF of the bug.
Way after I stopped clicking, the fruit detail section kept changing!
Let’s see my custom hook that leverages useEffect
.
Here’s the Codesandbox and GitHub links for reference.
The file is useFruitDetail.js
.
import { useEffect, useState } from 'react';import { getFruit } from './api';export const useFruitDetail = (fruitName) => {const [fruitDetail, setFruitDetail] = useState(null);useEffect(() => {if (!fruitName) {return;}getFruit(fruitName).then(setFruitDetail);},[fruitName]);return fruitDetail;};
Whenever fruitName
changes, we’ll request its details, but we have no way of canceling a request! So, quickly re-running this results in many state changes that we’re no longer interested in.
If you render this to the UI, you get a messy user experience where the detail section keeps flickering until the final request is resolved.
Ignoring old requests is trivial with RxJS.
It can do so much more than what I’ll demo here, so I highly recommend that you dive into it!
This portion of our code, the effect code, needs to change.
() => {
if (!fruitName) {
return;
}
getFruit(fruitName)
.then(setFruitDetail);
}
Instead of a Promise, let’s convert getFruit
into an Observable using the RxJS defer
function; and instead of .then
, we’ll call .subscribe
.
import { useEffect, useState } from 'react';import { defer } from 'rxjs';import { getFruit } from './api';export const useFruitDetail = (fruitName) => {const [fruitDetail, setFruitDetail] = useState(null);useEffect(() => {if (!fruitName) {return;}const subscription = defer(() => getFruit(fruitName)).subscribe(setFruitDetail);},[fruitName]);return fruitDetail;};
This doesn’t fix the issue yet; we still need to unsubscribe if fruitName
changes.
According to
So something like this:
import { useEffect, useState } from 'react';import { defer } from 'rxjs';import { getFruit } from './api';export const useFruitDetail = (fruitName) => {const [fruitDetail, setFruitDetail] = useState(null);useEffect(() => {if (!fruitName) {return;}const subscription = defer(() => getFruit(fruitName)).subscribe(setFruitDetail);return () => {subscription.unsubscribe();};},[fruitName]);return fruitDetail;};
Try running the app now; I’ve also posted a GIF of the final result below.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta name="theme-color" content="#000000"> <!-- manifest.json provides metadata used when your web app is added to the homescreen on Android. See https://developers.google.com/web/fundamentals/engage-and-retain/web-app-manifest/ --> <link rel="manifest" href="%PUBLIC_URL%/manifest.json"> <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico"> <!-- Notice the use of %PUBLIC_URL% in the tags above. It will be replaced with the URL of the `public` folder during the build. Only files inside the `public` folder can be referenced from the HTML. Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will work correctly both with client-side routing and a non-root public URL. Learn how to configure a non-root public URL by running `npm run build`. --> <title>React App</title> </head> <body> <noscript> You need to enable JavaScript to run this app. </noscript> <div id="root"></div> <!-- This HTML file is a template. If you open it directly in the browser, you will see an empty page. You can add webfonts, meta tags, or analytics to this file. The build step will place the bundled scripts into the <body> tag. To begin the development, run `npm start` or `yarn start`. To create a production bundle, use `npm run build` or `yarn build`. --> </body> </html>
This experience is much cleaner!
By clicking another fruit, useEffect
sees fruitName
change and runs the previous effect’s cleanup logic. As a result, we unsubscribe from the previous fetch call and focus on the current one.
Now our UI patiently waits until the user’s done clicking and the latest fruit’s details return.
Thanks for following this tutorial to the end! I’m on Twitter if you’d like to talk!
Take care,
Yazeed Bzadough
http://yazeedb.com/