الانتقال إلى المحتوى
FrontendReact· 7 دقائق للقراءة

Render Is Not the Place for Side Effects: Why Components Must Be Pure

React may run your component twice, restart it or skip it. Only a pure render survives that.

ReadIn

مقال كل يوم يفرق معاك

21 نوفمبر 2026
  • كاتب موثّق
  • React 19
محتويات المقال

The growth team's dashboard says the average visitor views each product page several times per visit, and nobody believes it. The cause is one line at the top of 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

The belief: the component body is just code that runs when the component shows up. If the UI looks right, then a log call, a counter or an analytics event in there is harmless.

It's an understandable belief. A function component's body reads like a script that runs "on show", the same way a constructor or an old 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

React's docs define a pure component with two rules. It minds its own business: it doesn't change objects or variables that existed before it was called. And same inputs, same output: given the same props, state and context, it returns the same JSX. A is anything else your code does that someone can observe: a network request, a write to the DOM or to localStorage, a change to a variable outside the component.

React may run render more or fewer times than you think

Because React assumes every component is a , it feels free to call it whenever that helps:

  • 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 useMemo functions 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. memo and 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 document doesn't exist.

So the number of renders says nothing about how many times the user saw something. Anything that must happen a specific number of times can't live in render.

Where side effects go instead

React gives you two places that run outside render. Event handlers come first: they run because the user did something, they're never called during render, and they don't need to be pure. Effects run after React commits, to synchronize with a system outside React, and the docs call them the last resort when no event fits. "The product page is now on screen" is one of those cases: there's no click, so the view event belongs in an Effect keyed on the product.

TSX ProductPage.tsx
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>    </>  );}

In the right version, picking a size re-renders 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

The other half of purity is not mutating inputs. A classic slip is sorting props during render:

TSX Leaderboard.tsx
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.

In the component bodyPure?Where it belongs
Filtering, sorting a copy, formatting props and stateYesRight where it is
Creating a local array or object and mutating itYesFine in render
track(), fetch(), writing localStorageNoAn event handler, or an Effect when nothing was clicked
document.title = ... or other DOM writesNoRender <title>, or sync in an Effect
props.items.sort(), counter++ on a module variableNoCopy first, or keep the value in state
new Date() or Math.random() in the outputNoInitialize state with it and update from an Effect or handler

How to apply it in your project

  1. Turn on the purity lintsUse the recommended preset of eslint-plugin-react-hooks. Its purity rule flags known impure calls during render, globals flags assignments to globals, and immutability flags mutated props and state.
  2. Keep Strict Mode onWrap your app in StrictMode and treat anything that appears twice in development as a bug report about render.
  3. Audit component bodies for calls that leave the componentLook 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.
  4. Copy before you change inputsNever call sort, reverse, push or assign fields on props, state or context. Use toSorted, 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.

📚 المصادر

  1. Keeping Components Pure — React
  2. Components and Hooks must be pure — Rules of React
  3. StrictMode: fixing bugs found by double rendering — React
  4. <title> — React DOM Components
  5. eslint-plugin-react-hooks — React

التعليقات (0)