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
- Event handlers for effects caused by a user action (submitting a form, clicking "Buy"). This is the preferred place.
useEffectfor synchronizing with an external system because the component is displayed (connecting to a chat room while the room view is visible).- Actions (React 19): async transitions and form actions for mutations, with pending and error handling.
- 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
1import { useEffect, useState } from "react";23let renderCount = 0; // module-level variable45export function Article({ id }: { id: string }) {6 const [liked, setLiked] = useState(false);78 // Side effect during render: impure, runs an unpredictable number of times9 // renderCount++; localStorage.setItem("lastArticle", id); fetch(`/api/view/${id}`);1011 // Effect: synchronize with an external system while displayed12 useEffect(() => {13 document.title = `Article ${id}`;14 navigator.sendBeacon?.("/api/view", id);15 }, [id]);1617 // Event handler: side effect caused by a specific user action18 async function like() {19 setLiked(true);20 await fetch(`/api/articles/${id}/like`, { method: "POST" });21 }2223 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.