ReactEasy

What is a side effect?

A side effect is anything a function does beyond computing its return value: changing something outside itself, such as making network requests, modifying the DOM directly, setting timers, writing to storage, logging, or mutating external variables. In React, rendering must be free of side effects; they belong in event handlers or effects.

Examples

  • Fetching data or posting to an API.
  • Subscribing to WebSockets, events or stores.
  • Starting timers.
  • Reading or writing localStorage, cookies, document.title.
  • Imperative DOM manipulation, focusing elements, integrating third-party widgets.
  • Analytics and logging.
  • Mutating objects created outside the component (including props and state).

Where they go in React

  1. Event handlers for effects caused by a user action (submitting a form, clicking "Buy"). This is the preferred place.
  2. useEffect for synchronizing with an external system because the component is displayed (connecting to a chat room while the room view is visible).
  3. Actions (React 19): async transitions and form actions for mutations, with pending and error handling.
  4. Data libraries and frameworks for fetching: TanStack Query, SWR, loaders, Server Components.

Why rendering must be pure

React may render a component multiple times, pause or discard renders (concurrent rendering), and Strict Mode intentionally double-renders in development. Side effects during render would run unpredictably. The React Compiler also assumes components and hooks are pure.

Code example

tsx
1import { useEffect, useState } from "react";
2
3let renderCount = 0; // module-level variable
4
5export function Article({ id }: { id: string }) {
6 const [liked, setLiked] = useState(false);
7
8 // Side effect during render: impure, runs an unpredictable number of times
9 // renderCount++; localStorage.setItem("lastArticle", id); fetch(`/api/view/${id}`);
10
11 // Effect: synchronize with an external system while displayed
12 useEffect(() => {
13 document.title = `Article ${id}`;
14 navigator.sendBeacon?.("/api/view", id);
15 }, [id]);
16
17 // Event handler: side effect caused by a specific user action
18 async function like() {
19 setLiked(true);
20 await fetch(`/api/articles/${id}/like`, { method: "POST" });
21 }
22
23 return <button onClick={like} disabled={liked}>{liked ? "Liked" : "Like"} {renderCount}</button>;
24}

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the React set.

Open in study app