What is a Side Effect?
You'll learn what "side effects" mean in React and why they're separate from your component's rendering logic.
The Core Idea
A side effect is any operation that reaches outside your component's render calculation. When React calls your component function, its main job is to calculate what JSX to return based on props and state. That's the "pure" part. Everything else — fetching data, setting timers, logging to the console, updating the DOM directly, subscribing to events — is a side effect.
Think of it this way: rendering is like doing math. Given the same inputs (props and state), you should get the same output (JSX). Side effects are like making phone calls while doing that math — they interact with the outside world.
Common Examples of Side Effects
Side effects include:
- Fetching data from an API
- Setting up timers with
setTimeoutorsetInterval - Subscribing to events (window resize, WebSocket connections)
- Logging to the console
- Writing to localStorage
- Directly manipulating the DOM
- Updating document.title
Not side effects:
- Calculating derived values from state
- Returning JSX
- Event handlers (onClick, onChange) — these respond to user actions, not render
Why This Matters
React keeps rendering pure and side effects separate for good reasons. During the Render Phase, React needs to be able to pause, restart, or discard renders without consequences. If you mixed side effects into your render logic, you'd get duplicate API calls, multiple timers, and chaos.
Side effects need to run after React finishes rendering and updating the DOM — that's what useEffect is for (coming in the next lessons).
Key Takeaway: Side effects are operations that reach beyond calculating JSX — they interact with the outside world and must be handled separately from rendering.