Single logo
  • Courses
  • Blog
  • About
Join on SkoolJoin on Skool

In this topic

React
  • One Request, Two Answers: the Same Post as an HTML Page and as JSON
  • A Blog Design from a Prompt: Downloading Figma Make Code and Reading App.tsx and BlogCard.tsx
  • How a Web Page Works: HTML Tags, Elements and Attributes
  • Semantic HTML: header, nav, main, aside and footer as Page Landmarks
  • HTML Forms: Labels, Names, Input Types and Where the Data Goes (GET vs POST)
  • CSS Basics: Selectors, Which Rule Wins, and the Box Model
  • CSS Flexbox vs Grid: A Nav Bar, a Card Row and a Dashboard
  • Responsive CSS: Viewport, Mobile-First Media Queries, clamp() and Dark Mode with Tokens
  • JavaScript for People Who Already Code: Syntax, Modules and Five Surprises
  • JavaScript Arrays the Functional Way: map, filter, reduce, find, sort and Object.entries
  • Async JavaScript: Promises, async/await, fetch and Promise.all
  • JavaScript in the Page: the DOM, querySelector and Events
  • npm, package.json and Vite: What npm install Fetches and How Vite Serves and Builds Your Page
  • TypeScript Essentials: Types Checked, Then Erased (Interfaces, Unions, Generics)
  • Why React, JSX and Components: The Page as a Function of Data
  • React Props and Composition: Data Down, Calls Up, Children in the Slot
  • Routing With React Router: One Page, Many Addresses
  • React Component Tests With Vitest and Testing Library: Test What the User Sees
  • End-to-End Tests for a React App With Playwright: A Full Dress Rehearsal
  • Why AI-Built Websites All Look the Same, and Four Levels That Fix It
  • Visual Hierarchy, Spacing and the 8-Point Grid: Tell the Eye What to Read First
  • Colour, Contrast and Dark Palettes: 60-30-10, Semantic Tokens and Ratios You Can Compute
  • Typography That Sells: Type Scale, Line Length and Free Font Pairings
  • The UI Element Catalogue: Buttons to Toasts, Their Jobs, States and shadcn/ui Names
  • Design Tokens: Primitive and Semantic Tokens, from Figma to CSS to Tailwind
  • Tailwind CSS 4 in React: Utility Classes, Responsive Prefixes, Hover and Dark Mode
  • shadcn/ui in React: Components You Own, Edit and Commit
  • Design Tokens to a Tailwind Theme: Light and Dark Mode with @theme inline
  • Motion in React: Entrance, Hover, Exit and Layout Animations
  • A React Dashboard: Stat Cards, a Recharts Line Chart and a Sortable Table
  • Accessibility in Practice: Dialogs, Menus and the Keyboard in React
  • Reference-Driven Design: Extract a DESIGN.md From a Site You Admire and Build From It
  • Components, Variants and Variables: One Design System in Figma and in CSS
  • Figma MCP Server: Build a React Component From a Frame, Then Write It Back
  • Claude Design: From a Brief to a Clickable Prototype, Then Hand It Off to Claude Code
  • Critiquing AI-Generated UI: Six Checks for Every Screen
  • The AI Design Landscape: Prompt to UI, Prompt to App, and Design to Code
  • Your Brand Rules Folder: One Folder Every AI-Built Page Follows
  • The Best-Practice UI Prompt: Plain Sentences That Beat the Average AI Page
  • UI Ideas From Figma Make, Google Stitch and ChatGPT: One Prompt, Three Designs
  • Google Stitch From a Sketch or Screenshot: Show the Layout, Say What to Keep
  • Stitch to Figma to Code: Turn a Stitch Screen Into Code That Uses Your Tokens
  • Figma Make: Prompt to Prototype With a Four-Part Prompt
  • Upgrade a Dated UI From One Screenshot (or a Reference Image)
  • States and Feedback: Make Every Click Get an Answer
  • A Design-Loop Skill: Claude Screenshots, Scores and Fixes Its Own UI
  • Copy Without the AI Tells: A Copy Pass on a Landing Page
  • React State, Events, Lists and Conditional Rendering: Follow One Click
  • React useEffect: When It Runs, What Cleanup Is For, and When You Don't Need One
  • Lifting State Up, Refs and React DevTools: Put State Where It Is Needed
  • Forms and Actions in React 19: Controlled Inputs, Form Actions, useActionState and useFormStatus
  • React Context and Custom Hooks: Share One Value, Reuse the Logic
  • Server State With TanStack Query: One Key, One Request, One Cache
  • Mutations and Optimistic Updates in TanStack Query: Change Data, Then Tell the Cache
  • Generate TypeScript Types, Query Hooks and Zod From an OpenAPI Spec With Orval
  • A Mock Backend in the Browser With Mock Service Worker, Generated From the Spec
  • A React Client for a FastAPI API: The CORS Wall, CORSMiddleware and the Vite Proxy
  • Forms With React Hook Form and Zod: The API's Rules in the Browser, the Server's Errors Under the Field
  • JWT Auth in a React Client With a FastAPI Backend: Log In, Carry the Token, Let the Server Decide
  1. Blog
  2. /
  3. React
  4. /
  5. Hooks

React useEffect: When It Runs, What Cleanup Is For, and When You Don't Need One

Watch useEffect on a timeline with real render counts: the dependency array deciding re-runs, a timer cleanup that keeps one timer alive, the leak StrictMode exposes, and two effects you should delete (a copied total and a click flag).

Chaand Sheikh

·27 November 2026·Updated 28 November 2026Hooks

What you will learn

  • Place an effect on the timeline: render, page update, then effect
  • Predict re-runs from the dependency array: none, empty or with values
  • Write a cleanup that stops what the effect started, and see why StrictMode runs it twice
  • Replace effects that copy values or react to clicks with render-time code or event handlers

Before you start

  • React state with useState
  • JavaScript timers: setInterval and clearInterval

An effect is for one job: keeping something outside React in sync with your component. The browser tab title, a timer, a request to a server, a listener on the window. React can't draw those for you, so you reach out to them after the page is ready.

This article puts effects on a timeline and counts every render, using the lecture's small demos. The second half is just as useful: two effects you should delete.

Render, page, then the effect

The order of render, page update and effect 1. Render React calls TaskTitle 2. Page button shows Done: 0 3. Effect tab: 0 tasks done outside React
The effect never runs in the middle of a render. It waits until the page is up to date.
import { useEffect, useState } from 'react'

export default function TaskTitle() {
  const [done, setDone] = useState(0)
  const [dark, setDark] = useState(false)
  console.log('render:', { done, dark })

  useEffect(() => {
    // runs AFTER React has updated the page
    document.title = `${done} tasks done`
    console.log('effect: title =', document.title)
  }, [done]) // again only when done changes

  const add = () => setDone(done + 1)
  const flip = () => setDark(!dark)
  return (
    <div className={dark ? 'card dark' : 'card'}>
      <button onClick={add}>Done: {done}</button>
      <button onClick={flip}>Dark</button>
    </div>
  )
}

On the first render the logs come out in exactly that order:

render: { done: 0, dark: false }
page: Done: 0
effect: title = 0 tasks done

The dependency array decides re-runs

Line 12, [done], is the dependency array. After the effect runs, React remembers it. After every later render, React compares the new array with the old one. Different values: the effect runs again. Same values: it is skipped. Click Done, then Dark:

render: { done: 0, dark: false }
effect: title = 0 tasks done
click: Done
render: { done: 1, dark: false }
effect: title = 1 tasks done
click: Dark
render: { done: 1, dark: true }
effect ran 2 times in 3 renders

Clicking Done changes done from 0 to 1, so [1] differs from [0] and the title updates. Clicking Dark renders a third time, but done is still 1, so the effect is skipped. Two effect runs in three renders.

Three ways to write the array

const runs = { none: 0, empty: 0, done: 0 }
function Probe() {
  const [done, setDone] = useState(0)
  const [dark, setDark] = useState(false)
  useEffect(() => { runs.none++ })
  useEffect(() => { runs.empty++ }, [])
  useEffect(() => { runs.done++ }, [done])
  const add = () => setDone(done + 1)
  const flip = () => setDark(!dark)
  return <>
    <button onClick={add}>Done</button>
    <button onClick={flip}>Dark</button>
  </>
}
await show(<Probe />) // render 1
await click('Done', false) // render 2: done changes
await click('Dark', false) // render 3: dark only
console.log('no array:', runs.none, 'times')
console.log('[]:      ', runs.empty, 'time')
console.log('[done]:  ', runs.done, 'times')
no array: 3 times
[]:       1 time
[done]:   2 times
ArrayRunsHere
noneafter every render3 times
[]once, after the first render1 time
[done]first render, then whenever done changes2 times

Cleanup: stop what the effect started

import { useEffect, useState } from 'react'

export default function Ticker() {
  const [ticks, setTicks] = useState(0)
  const [delay, setDelay] = useState(1000)
  useEffect(() => {
    console.log('effect: start', delay, 'ms timer')
    const tick = () => setTicks((t) => t + 1)
    const id = setInterval(tick, delay)
    return () => {
      // still the delay this effect started with
      console.log('cleanup: stop', delay, 'ms timer')
      clearInterval(id)
    }
  }, [delay])
  const faster = () => setDelay(500)
  return (
    <div className="card">
      <p>Ticks: {ticks}</p>
      <button onClick={faster}>Faster</button>
    </div>
  )
}

After the first render, the effect starts a browser timer with setInterval. Every second it calls setTicks((t) => t + 1), which always adds one to the latest value. Line 10 returns a function: the cleanup.

Click Faster and delay becomes 500. The array changed, so the effect must run again. But first React runs the old effect's cleanup, and that old cleanup still sees delay as 1000, the value from its own render:

effect: start 1000 ms timer
after 2 s: Ticks: 2, timers running: 1
click: Faster
cleanup: stop 1000 ms timer
effect: start 500 ms timer
after 1 s: Ticks: 4, timers running: 1

One timer stopped, one started, and never two at once. The cleanup also runs when the component goes away (unmounts):

effect: start 1000 ms timer
click: Faster
cleanup: stop 1000 ms timer
effect: start 500 ms timer
unmount
cleanup: stop 500 ms timer
timers running: 0

Every effect run has its cleanup: start 1000, stop 1000, start 500, stop 500. Nothing is left behind.

StrictMode runs it twice, on purpose

import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'
import './index.css'
import App from './App'

// development only: React runs every effect,
// its cleanup, then the effect again
createRoot(document.getElementById('root')!).render(
  <StrictMode>
    <App />
  </StrictMode>,
)

A Vite React app wraps App in StrictMode. It is on only in development (npm run dev), not in the build you publish. When a component appears, StrictMode runs the effect, then its cleanup, then the effect again, as a fake unmount and mount that tests your cleanup:

effect: start 1000 ms timer
cleanup: stop 1000 ms timer
effect: start 1000 ms timer
after 2 s: Ticks: 2, timers running: 1

Because the cleanup is right, the second run is harmless: Ticks: 2 after two seconds, one timer.

No cleanup: two timers

function LeakyTicker() {
  const [ticks, setTicks] = useState(0)
  useEffect(() => {
    console.log('effect: start a timer, no cleanup')
    setInterval(() => setTicks((t) => t + 1), 1000)
  }, [])
  return <p>Ticks: {ticks}</p>
}
effect: start a timer, no cleanup
effect: start a timer, no cleanup
after 2 s: Ticks: 4
timers running: 2

StrictMode started the effect twice and nothing stopped the first timer, so the clock runs at double speed. StrictMode doesn't cause this bug, it shows it. Every effect that starts something needs a cleanup.

Do you need an effect at all?

Effect, render or event handler Outside React to sync? tab title, timer, server request, window listener useEffect + cleanup From props and state? a total, a filtered list, a full name compute in render Caused by a click? save a task, show a message do it in the handler
Only the first column needs an effect. The other two are simpler, and need fewer renders, without one.

A value copied by an effect

import { useEffect, useState } from 'react'

type Props = { price: number }

// the same cart, with the total copied by an effect
export default function Cart({ price }: Props) {
  const [qty, setQty] = useState(1)
  const [total, setTotal] = useState(0)
  console.log('render:', { qty, total })

  useEffect(() => {
    setTotal(price * qty) // one more render, to copy
  }, [price, qty])

  const add = () => setQty(qty + 1)
  return (
    <div className="card">
      <p>Qty: {qty} Total: {total}</p>
      <button onClick={add}>+1</button>
    </div>
  )
}
render: { qty: 1, total: 0 }
render: { qty: 1, total: 15 }
click: +1
render: { qty: 2, total: 15 }
render: { qty: 2, total: 30 }
renders: 4

Render 1 shows Total: 0, which is wrong. The effect sets the total, which costs another render. Click +1 and render 3 still shows 15, wrong again, until the effect fixes it in render 4. Two renders for every change, to copy a value React already knew. Work it out during the render instead:

import { useState } from 'react'

type Props = { price: number }

export default function Cart({ price }: Props) {
  const [qty, setQty] = useState(1)
  const total = price * qty // worked out in render
  console.log('render:', { qty, total })

  const add = () => setQty(qty + 1)
  return (
    <div className="card">
      <p>Qty: {qty} Total: {total}</p>
      <button onClick={add}>+1</button>
    </div>
  )
}
render: { qty: 1, total: 15 }
click: +1
render: { qty: 2, total: 30 }
renders: 2

Right the first time, and two renders instead of four for the same two steps.

A click handled by an effect

import { useEffect, useState } from 'react'

// the same button, the click handled by an effect
export default function Save() {
  const [saved, setSaved] = useState(false)
  const [message, setMessage] = useState('')
  console.log('render:', { saved, message })

  useEffect(() => {
    if (saved) setMessage('Task saved')
  }, [saved])

  const save = () => setSaved(true)
  return (
    <div className="card">
      <button onClick={save}>Save</button>
      <p>{message}</p>
    </div>
  )
}
render: { saved: false, message: '' }
click: Save
render: { saved: true, message: '' }
render: { saved: true, message: 'Task saved' }
page: Task saved
renders: 3

The click only sets a flag. The message appears one render late, after the effect notices the flag. When a click is the reason, the handler is the place:

import { useState } from 'react'

export default function Save() {
  const [message, setMessage] = useState('')
  console.log('render:', { message })

  function save() {
    // the click is the reason, so the work goes here
    setMessage('Task saved')
  }

  return (
    <div className="card">
      <button onClick={save}>Save</button>
      <p>{message}</p>
    </div>
  )
}
render: { message: '' }
click: Save
render: { message: 'Task saved' }
page: Task saved
renders: 2

Recap

IdeaWhat to remember
TimingRender, page update, then the effect
Dependency arrayCompared after every render; same values mean the effect is skipped
CleanupRuns before the next effect and on unmount; it sees its own render's values
StrictModeDevelopment only: effect, cleanup, effect; a good cleanup makes it harmless
Derived valuesCompute in render, no state, no effect
ClicksDo the work in the event handler

Try it yourself: add a "Slower" button to the Ticker that sets the delay to 2000, and predict the cleanup and effect lines before you click it. Next: lifting state up, refs and React DevTools.

Keep going in React · 49 of 59

Previous
React State, Events, Lists and Conditional Rendering: Follow One Click
Next post
Lifting State Up, Refs and React DevTools: Put State Where It Is Needed
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

Related course on Udemy

The Python Architect Masterclass: Full Stack to AI Engineer

Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)

Related posts

React State, Events, Lists and Conditional Rendering: Follow One Click

Follow one click through a React counter, render by render: what useState hands back, why a plain variable never updates the page, ternaries and &&, map with keys, and the index-as-key bug that moves a typed note to the wrong task.

Lifting State Up, Refs and React DevTools: Put State Where It Is Needed

A task board where the filter is stuck in one component, fixed by lifting it to App. Then useRef as a box React does not watch (three clicks, zero renders), a ref that refocuses an input, and the tree React DevTools shows.

Forms and Actions in React 19: Controlled Inputs, Form Actions, useActionState and useFormStatus

Four versions of an add-task form, traced with real logs: a controlled input, a classic onSubmit, a form action that gets FormData and resets itself, and useActionState with a pending button from useFormStatus, plus the draft trick that keeps typed text after an error.

React Context and Custom Hooks: Share One Value, Reuse the Logic

Replace three hops of prop drilling with a context, see the nearest Provider win, count which components re-render on a theme toggle, then pull localStorage logic into a useLocalStorage hook and break the rules of hooks on purpose.

On this page

  • Render, page, then the effect
  • The dependency array decides re-runs
  • Three ways to write the array
  • Cleanup: stop what the effect started
  • StrictMode runs it twice, on purpose
  • No cleanup: two timers
  • Do you need an effect at all?
  • A value copied by an effect
  • A click handled by an effect
  • Recap
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

Related course on Udemy

The Python Architect Masterclass: Full Stack to AI Engineer

Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)

Single logo

Empowering Education, One Course at a Time

About
About usContact us
Legal
Terms of UsePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.