React, deeply · Chapter 3 of 12 · Web · new chapter every Monday night
By the end of this chapter: Identify the small number of cases useEffect is for, and the far larger number where it is the wrong tool.
The problem
Emma, a front-end engineer, is working on a real-time analytics dashboard with a two-month sprint deadline. The dashboard updates a table every second with live metrics from a WebSocket. After adding a "filter by region" feature, the dashboard started experiencing issues: the table lags by up to three seconds, the CPU usage on the user's laptop spikes to 90%, and the performance monitoring alert fires every time a user opens the page. The team cannot afford to roll back the feature, and the sprint deadline is only three days away. Emma needs to identify the cause of the problem and fix it quickly.
The issue seems to be related to the way the state is being updated and the effects that are being run after each update. Emma has been using useEffect to handle the side effects of updating the table, but she's not sure if she's using it correctly. She's also not sure if there are other factors contributing to the performance issues.
Emma's current implementation uses useEffect to fetch new data from the WebSocket and update the table every second. However, she's noticed that the useEffect hook is being run more frequently than expected, causing the CPU usage to spike. She's tried to optimize the code by using useCallback and useMemo, but the issue persists.
Before you start
To follow along with this chapter, you should have a good understanding of React's rendering and reconciliation process, as well as the different state mechanisms available in React, such as useState and useReducer. You should also have a basic understanding of how to use useEffect to handle side effects in your React components.
Make sure you have the following installed:
- Node.js (version 16 or later)
- npm (version 8 or later)
- React (version 18 or later)
- A code editor or IDE of your choice
You can verify that you have the correct versions installed by running the following commands in your terminal:
node -v
npm -v
npm ls react
Understanding useEffect
useEffect is a powerful hook in React that allows you to run side effects after rendering a component. However, it's often misused or overused, leading to performance issues like the one Emma is experiencing.
To understand how useEffect works, let's break down its signature:
useEffect(effect, dependencies)
The effect function is the code that will be run after rendering the component, and the dependencies array specifies which values the effect depends on. If any of the values in the dependencies array change, the effect will be re-run.
When to use useEffect
So, when should you use useEffect? Here are some scenarios where useEffect is the right tool for the job:
- Fetching data from an API or WebSocket
- Setting up event listeners or subscriptions
- Updating the DOM directly (although this should be avoided whenever possible)
However, there are many cases where useEffect is not the right tool. For example:
- Updating state based on user input
- Running computations that don't have side effects
- Handling errors or exceptions
In these cases, other hooks like useState, useReducer, or useCallback might be more suitable.
Build it
Let's take a look at Emma's code and see where she might be going wrong. Here's an example of her useEffect hook:
import { useEffect, useState } from 'react';
function Dashboard() {
const [data, setData] = useState([]);
const [filter, setFilter] = useState('all');
useEffect(() => {
const socket = new WebSocket('ws://example.com/data');
socket.onmessage = (event) => {
setData(JSON.parse(event.data));
};
return () => {
socket.close();
};
}, [filter]);
return (
<table>
{data.map((row) => (
<tr key={row.id}>
<td>{row.name}</td>
<td>{row.value}</td>
</tr>
))}
</table>
);
}
The problem with this code is that the useEffect hook is being run every time the filter state changes, which is causing the WebSocket connection to be reopened and closed repeatedly. This is likely causing the CPU usage to spike and the table to lag.
To fix this issue, Emma can use the useEffect hook with an empty dependencies array, like this:
useEffect(() => {
const socket = new WebSocket('ws://example.com/data');
socket.onmessage = (event) => {
setData(JSON.parse(event.data));
};
return () => {
socket.close();
};
}, []);
This will ensure that the useEffect hook is only run once, when the component mounts, and not every time the filter state changes.
When this breaks
There are several ways that the useEffect hook can break, including:
- Running the effect too frequently, causing performance issues
- Failing to clean up after the effect, causing memory leaks
- Not handling errors or exceptions properly
To avoid these issues, make sure to:
- Use the
useEffecthook with caution and only when necessary - Always clean up after the effect by returning a function from the
useEffecthook - Handle errors and exceptions properly using try-catch blocks and error boundaries
What it costs
Using useEffect can come with a cost, including:
- Performance issues if the effect is run too frequently
- Memory leaks if the effect is not cleaned up properly
- Complexity and debugging issues if the effect is not handled properly
To minimize these costs, make sure to:
- Use the
useEffecthook only when necessary - Optimize the effect to run as infrequently as possible
- Use tools like the React DevTools to debug and optimize the effect
In the interview
When interviewing for a front-end engineering position, you may be asked questions about useEffect and how to use it properly. Here are some example questions and answers:
Q: What is useEffect and how does it work?
A: useEffect is a hook in React that allows you to run side effects after rendering a component. It takes two arguments: the effect function and the dependencies array. The effect function is run after rendering the component, and the dependencies array specifies which values the effect depends on.
Q: When should you use useEffect?
A: You should use useEffect when you need to run a side effect after rendering a component, such as fetching data from an API or setting up event listeners.
Q: What are some common mistakes people make when using useEffect?
A: Some common mistakes people make when using useEffect include running the effect too frequently, failing to clean up after the effect, and not handling errors or exceptions properly.
Your tasks
- Create a simple React component that uses
useEffectto fetch data from an API and update the component's state. - Optimize the component to run the effect as infrequently as possible.
- Use the React DevTools to debug and optimize the component.
- Write a test for the component to ensure it is working correctly.
- Refactor the component to use a different hook, such as
useCallbackoruseMemo, to see if it improves performance.
Your tasks this week
Do the exercises above before the next chapter. Reading a tutorial and doing
one are different activities and only one of them changes what you can build.
Stuck on any of them? Say so — describe what you tried and what happened:
tell me where you got stuck. I read every one, and the questions
that come back more than twice get answered in the next chapter.
React, deeply
Chapter 3 of 12. New chapter every Monday night.
Next: Data fetching: Suspense, transitions and cache boundaries.
· The full syllabus and every chapter so far
· Subscribers also get the condensed notes for this chapter, the running
recap of everything the series has covered, and the extended guidance:
subscribe
Written by Amit Chakraborty — founding engineer and senior architect: React Native, AI and RAG systems, production architecture. Portfolio · LinkedIn · GitHub.
Need this built, reviewed or taught to your team? Get in touch or email amit@devamit.co.in. Available for senior and founding engineering roles, consulting and training, remote worldwide.
Top comments (0)