
Render Is Not the Place for Side Effects: Why Components Must Be Pure
- كاتب موثّق
- React 19
محتويات المقال
ProductPage: track("product_view", product.id). It sits in the component body, so every re-render counts as a view: picking a size, changing the quantity, a price refresh. In development every view was logged twice, and the team had shrugged that off as React being strange in dev mode.
The common misconception
componentDidMount did. In a simple app, each update usually renders once, so the side effect seems to fire at the right moment. And there's a true part: React doesn't demand purity in the strict mathematical sense. Its rules say it doesn't mind small impurities, as long as calling the component several times is safe and doesn't affect the rendering of other components. Analytics, DOM writes and changed outside variables fail exactly that test.
What actually happens
Render is a calculation
localStorage, a change to a variable outside the component.
React may run render more or fewer times than you think
Every re-render. As the earlier articles in this path showed, a state change, a parent's render or a context update runs the body again, even when nothing the user sees has changed. Twice in development. Strict Mode calls your component body, state initializers, updaters and useMemofunctions twice to expose impure code. Production builds skip this.A render thrown away. If data changes in the middle of rendering a deep tree, React can restart and discard the unfinished render. A side effect inside it already happened anyway. A render skipped. memoand React Compiler skip renders whose inputs haven't changed, which is only safe because pure output can be cached. A side effect there silently doesn't run.A render somewhere else. The same component can render on the server, where documentdoesn't exist.
Where side effects go instead
import { useState } from "react";export function ProductPage({ product }: { product: Product }) { const [size, setSize] = useState("M"); // Runs on every render: picking a size logs another "view" track("product_view", product.id); // A DOM write from a render React may repeat or discard document.title = product.name; return ( <> <SizePicker value={size} onChange={setSize} /> <button onClick={() => addToCart(product.id, size)}>Add to cart</button> </> );}import { useEffect, useState } from "react";export function ProductPage({ product }: { product: Product }) { const [size, setSize] = useState("M"); // After commit, once per product: syncing with the outside world useEffect(() => { track("product_view", product.id); }, [product.id]); function handleAdd() { track("add_to_cart", product.id); // caused by a click, so it lives here addToCart(product.id, size); } return ( <> <title>{product.name}</title> <SizePicker value={size} onChange={setSize} /> <button onClick={handleAdd}>Add to cart</button> </> );}ProductPage but sends nothing: the Effect runs again only when product.id changes. The add-to-cart event fires once per click because it lives in the handler. And the title is now part of the output: React renders <title> from any component into the document head, so there's no DOM write in render at all.
Changing what you were given
type Player = { id: string; name: string; score: number };export function Leaderboard({ players }: { players: Player[] }) { // players.sort(...) would reorder the parent's array in place, mid-render. // toSorted() returns a copy created in this render, which is yours to change. const ranked = players.toSorted((a, b) => b.score - a.score); return <ol>{ranked.map((p) => <li key={p.id}>{p.name}</li>)}</ol>;}sort() changes the array the parent owns, so the parent's own list, and every other component sharing that array, silently changes order. Creating an object or array during render and then mutating it is fine, though; React's docs call that local mutation, and nobody outside can tell.
track(), fetch(), writing localStorage | ||
document.title = ... or other DOM writes | <title>, or sync in an Effect | |
props.items.sort(), counter++ on a module variable | ||
new Date() or Math.random() in the output |
How to apply it in your project
Turn on the purity lints Use the recommended preset of eslint-plugin-react-hooks. Itspurityrule flags known impure calls during render,globalsflags assignments to globals, andimmutabilityflags mutated props and state.Keep Strict Mode on Wrap your app in StrictModeand treat anything that appears twice in development as a bug report about render.Audit component bodies for calls that leave the component Look for requests, analytics, timers, storage and DOM access at the top level of components. Move each one to the event handler that caused it, or to an Effect if it syncs with what's on screen. Copy before you change inputs Never call sort,reverse,pushor assign fields on props, state or context. UsetoSorted, spread or a local copy instead.
Key takeaways
A pure component returns the same JSX for the same props, state and context, and changes nothing that existed before it ran. React may render twice, restart, skip or move a render to the server, so render count isn't a measure of anything. Side effects belong in event handlers first, and in Effects when they sync with something outside React. Local mutation is fine; mutating props, state or outside variables is not, and Strict Mode plus the lints catch it.
التعليقات (0)