Skip to main content

Web frameworks · Intermediate · 25 min

Use useEffect correctly in React, and know when you don't need it

By Padding · Updated 18 Nov 2026
Node.js 26.13 LTS (node:26 image) · React 19.3.1 · Vite 8.3

You will write React 19.3 effects that subscribe, time and connect with proper cleanup and dependencies, fix a stale-data race in a fetch effect, and delete three effects that should never have existed.

On this page

useEffect is the hook people reach for when something has to happen "after render". That is too broad. An effect exists to keep a component in step with something React does not control: a browser event, a timer, a network connection. Used for that, it needs two things most bugs come from missing, a cleanup function and an honest dependency array. Used for anything else, it adds extra renders, flashes of stale data and code that runs at the wrong moment.

In this tutorial you build a small "effects lab" page with Vite, React 19.3 and TypeScript. First you write three effects that earn their place: a window size listener, a timer and a live exchange-rate feed that behaves like a WebSocket. You watch React's development mode run each one twice, and learn why. Then you break and fix a data-fetching effect that shows the wrong person, and finally you remove three effects by replacing them with plain render code, a key and an event handler.

Commands are for a Linux or macOS shell, or WSL on Windows. You need two terminals: one for the dev server, one for everything else.

Step 1 · Create the effects lab project

Scaffold a React and TypeScript project with Vite's create-vite tool, then pin React to an exact version so what you see matches this page:

Bash
cd ~
npm create vite@9.3.4 effects-lab -- --template react-ts --no-interactive
cd effects-lab
npm install
npm install --save-exact react@19.3.1 react-dom@19.3.1

Remove the starter page and its assets, and replace src/App.tsx with an empty shell:

Bash
rm -rf src/assets src/App.css
cat > src/App.tsx <<'TSX'
export default function App() {
  return (
    <main>
      <h1>Effects lab</h1>
    </main>
  )
}
TSX
cat src/main.tsx

Look at the last file printed. src/main.tsx renders <App /> inside <StrictMode>. Leave that in place: StrictMode is what exposes missing cleanups later in this tutorial, and it does nothing in a production build.

Start the dev server in your first terminal and leave it running:

Bash
npm run dev

Check it worked

The terminal shows VITE v8. followed by a version and Local: http://localhost:5173/. Open that address: the page shows the heading "Effects lab" and nothing else. Open the browser's developer tools on the Console tab and keep them open for the rest of the tutorial.

Step 2 · Subscribe to window resizes and clean up

The window's width lives outside React. When it changes, the browser fires a resize event, and the component must listen for it while it is on screen and stop listening when it leaves. Create src/WindowWidth.tsx:

Bash
cat > src/WindowWidth.tsx <<'TSX'
import { useEffect, useState } from 'react'

export default function WindowWidth() {
  const [width, setWidth] = useState(window.innerWidth)

  useEffect(() => {
    function handleResize() {
      setWidth(window.innerWidth)
    }
    window.addEventListener('resize', handleResize)
    return () => {
      window.removeEventListener('resize', handleResize)
    }
  }, [])

  return (
    <section>
      <h2>Window</h2>
      <p data-testid="width">Width: {width}px</p>
    </section>
  )
}
TSX
cat > src/App.tsx <<'TSX'
import WindowWidth from './WindowWidth'

export default function App() {
  return (
    <main>
      <h1>Effects lab</h1>
      <WindowWidth />
    </main>
  )
}
TSX

Read the effect as two halves. The setup adds a listener. The function it returns is the cleanup, and React calls it before the component is removed and before the effect runs again. The cleanup must undo exactly what the setup did, which is why handleResize is a named function: removeEventListener needs the same function object that addEventListener received.

The empty array [] means the effect reads nothing from props or state, so it never needs to re-run. That is a statement about the code, not a wish: if the effect used a prop, the prop would have to be in the array.

For a value like this that the browser stores and announces through events, React also offers useSyncExternalStore, which handles subscribing for you. The effect version is shown here because the setup-and-cleanup shape is the one every other effect in this tutorial follows.

Check it worked

The page shows a "Window" section with Width: and a number of pixels. Drag the edge of the browser window, or open the device toolbar in the developer tools and change the width: the number follows as you go.

Step 3 · Run a timer and a live feed, and see StrictMode at work

Two more outside systems. A timer from setInterval keeps running until you clear it. A network connection, such as a WebSocket, stays open until you close it. Create a small stand-in for a WebSocket in src/rateFeed.ts. It logs when it connects and disconnects, and sends a new exchange rate every 300 milliseconds:

Bash
cat > src/rateFeed.ts <<'TS'
// A stand-in for a WebSocket: it connects, sends messages, and must be closed.
const startRates: Record<string, number> = {
  'USD/NGN': 1450,
  'USD/KES': 129,
  'USD/GHS': 11.2,
}

export class RateFeed extends EventTarget {
  #timer: ReturnType<typeof setInterval>
  pair: string

  constructor(pair: string) {
    super()
    this.pair = pair
    console.log(`connect ${pair}`)
    let rate = startRates[pair] ?? 1
    this.#timer = setInterval(() => {
      rate = Math.round(rate * (1 + (Math.random() - 0.5) / 100) * 100) / 100
      this.dispatchEvent(new CustomEvent('rate', { detail: rate }))
    }, 300)
  }

  close() {
    clearInterval(this.#timer)
    console.log(`disconnect ${this.pair}`)
  }
}
TS

The rates are made up. Now the two components. Clock counts seconds since it appeared. RateTicker connects to the feed for the currency pair you pick:

Bash
cat > src/Clock.tsx <<'TSX'
import { useEffect, useState } from 'react'

export default function Clock() {
  const [seconds, setSeconds] = useState(0)

  useEffect(() => {
    const id = setInterval(() => {
      setSeconds((s) => s + 1)
    }, 1000)
    return () => clearInterval(id)
  }, [])

  return (
    <section>
      <h2>Timer</h2>
      <p data-testid="seconds">Open for {seconds} s</p>
    </section>
  )
}
TSX
cat > src/RateTicker.tsx <<'TSX'
import { useEffect, useState } from 'react'
import { RateFeed } from './rateFeed'

export default function RateTicker() {
  const [pair, setPair] = useState('USD/NGN')
  const [rate, setRate] = useState<number | null>(null)

  useEffect(() => {
    const feed = new RateFeed(pair)
    function handleRate(event: Event) {
      setRate((event as CustomEvent<number>).detail)
    }
    feed.addEventListener('rate', handleRate)
    return () => {
      feed.removeEventListener('rate', handleRate)
      feed.close()
    }
  }, [pair])

  return (
    <section>
      <h2>Live rate</h2>
      <label>
        Pair{' '}
        <select
          value={pair}
          onChange={(event) => {
            setPair(event.target.value)
            setRate(null)
          }}
        >
          <option>USD/NGN</option>
          <option>USD/KES</option>
          <option>USD/GHS</option>
        </select>
      </label>
      <p data-testid="rate">{rate === null ? 'Waiting…' : `${pair}: ${rate}`}</p>
    </section>
  )
}
TSX
cat > src/App.tsx <<'TSX'
import WindowWidth from './WindowWidth'
import Clock from './Clock'
import RateTicker from './RateTicker'

export default function App() {
  return (
    <main>
      <h1>Effects lab</h1>
      <WindowWidth />
      <Clock />
      <RateTicker />
    </main>
  )
}
TSX

Three details carry the lesson:

  • The timer calls setSeconds((s) => s + 1), not setSeconds(seconds + 1). The effect runs once, so a callback that read seconds directly would see the value from the first render, 0, for ever, and the clock would stop at 1. The updater form asks React for the current value instead, which keeps the dependency array honestly empty.
  • RateTicker lists [pair] because the effect reads pair. When you pick another pair, React runs the old cleanup (close the USD/NGN feed) and then the new setup (open the USD/KES one). That is the whole job of the dependency array: it says when the outside connection is out of date.
  • Every effect returns a cleanup. A timer or connection left running after its component has gone keeps using battery and, for a real socket, mobile data. On a low-end Android phone on a prepaid bundle, that cost is the user's.

Now look at the Console tab after the page reloads. You see connect USD/NGN, then disconnect USD/NGN, then connect USD/NGN again. This is StrictMode. In development, React mounts each component, immediately runs every effect's cleanup, and then runs the setup a second time. If your cleanup is missing or incomplete, you see two connections, two timers or a doubled count straight away, rather than weeks later when a user opens and closes the same screen many times. A production build does not do this; you confirm it in the last step.

Run the linter that came with the template. Its default rules include the React hooks checks:

Bash
npm run lint

Check it worked

The page shows "Open for" with a count that goes up by one each second, and a "Live rate" line such as USD/NGN: 1449.12 that changes several times a second. The Console tab shows the connect, disconnect, connect sequence once. Choose USD/KES in the menu: the console adds disconnect USD/NGN and then connect USD/KES, and the rate switches pair. npm run lint reports no warnings.

To see the linter catch a dishonest dependency array, change }, [pair]) in RateTicker.tsx to }, []) and run npm run lint again. It prints a react-hooks(exhaustive-deps) warning naming the missing pair, and in the browser the menu no longer changes the feed. Put pair back before you continue.

Step 4 · Fix a race condition in a fetch effect

Loading data when a value changes is the effect people write most often, and it has a trap. Requests do not finish in the order you sent them. Create a fake API in src/members.ts that answers after a different delay for each member, as real requests do when one record is slower to load:

Bash
cat > src/members.ts <<'TS'
export type Member = { id: number; name: string; city: string }

const members: Member[] = [
  { id: 1, name: 'Ada', city: 'Lagos' },
  { id: 2, name: 'Kofi', city: 'Accra' },
  { id: 3, name: 'Thandi', city: 'Durban' },
]

// Each member takes a different time to arrive, like real requests do.
const delays: Record<number, number> = { 1: 1500, 2: 200, 3: 600 }

export function fetchMember(id: number): Promise<Member> {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      const member = members.find((m) => m.id === id)
      if (member) resolve(member)
      else reject(new Error(`No member ${id}`))
    }, delays[id] ?? 500)
  })
}

export const memberIds = members.map((m) => ({ id: m.id, name: m.name }))
TS

Now write the version most codebases start with. It looks correct:

Bash
cat > src/MemberCard.tsx <<'TSX'
import { useEffect, useState } from 'react'
import { fetchMember, memberIds } from './members'
import type { Member } from './members'

export default function MemberCard() {
  const [id, setId] = useState(3)
  const [member, setMember] = useState<Member | null>(null)

  useEffect(() => {
    fetchMember(id).then((data) => {
      setMember(data)
    })
  }, [id])

  return (
    <section>
      <h2>Member</h2>
      {memberIds.map((m) => (
        <button key={m.id} aria-pressed={m.id === id} onClick={() => setId(m.id)}>
          {m.name}
        </button>
      ))}
      <p data-testid="member">{member ? `${member.name}, ${member.city}` : 'Loading…'}</p>
    </section>
  )
}
TSX
cat > src/App.tsx <<'TSX'
import WindowWidth from './WindowWidth'
import Clock from './Clock'
import RateTicker from './RateTicker'
import MemberCard from './MemberCard'

export default function App() {
  return (
    <main>
      <h1>Effects lab</h1>
      <WindowWidth />
      <Clock />
      <RateTicker />
      <MemberCard />
    </main>
  )
}
TSX

Click Ada, then click Kofi straight away, within a second. Kofi's button is the selected one, and for a moment the card shows Kofi, Accra. Then it changes to Ada, Lagos and stays there. Ada's request was sent first but finished last, and nothing stopped it overwriting the newer answer. On a slow or patchy mobile connection, where response times vary a lot, users hit this without trying.

The cleanup function is the fix. Each run of the effect gets its own ignore variable. When id changes, React runs the previous cleanup, which marks that run's answer as unwanted:

Bash
cat > src/MemberCard.tsx <<'TSX'
import { useEffect, useState } from 'react'
import { fetchMember, memberIds } from './members'
import type { Member } from './members'

export default function MemberCard() {
  const [id, setId] = useState(3)
  const [member, setMember] = useState<Member | null>(null)

  useEffect(() => {
    let ignore = false
    fetchMember(id).then((data) => {
      if (!ignore) {
        setMember(data)
      }
    })
    return () => {
      ignore = true
    }
  }, [id])

  return (
    <section>
      <h2>Member</h2>
      {memberIds.map((m) => (
        <button key={m.id} aria-pressed={m.id === id} onClick={() => setId(m.id)}>
          {m.name}
        </button>
      ))}
      <p data-testid="member">{member ? `${member.name}, ${member.city}` : 'Loading…'}</p>
    </section>
  )
}
TSX

With the real fetch, you can go one better and cancel the request: create an AbortController in the effect, pass { signal: controller.signal } to fetch, and call controller.abort() in the cleanup. Either way, this effect is still missing caching, retries and error states, which is why most apps hand data fetching to a library or a framework; the TanStack Query tutorial linked at the end takes that route.

Check it worked

Repeat the clicks: click Ada, then Kofi quickly. The card shows Kofi, Accra and stays on it after Ada's slow answer arrives, because that answer is ignored. Click any one name and wait: the card always ends on the member whose button is selected.

Step 5 · Remove an effect that calculates a derived value

From here on you delete effects. The first kind copies a value that can be worked out from existing state into more state. Create a basket in src/Basket.tsx the way it is often written, with the total kept in sync by an effect:

Bash
cat > src/Basket.tsx <<'TSX'
import { useEffect, useState } from 'react'

type Line = { name: string; price: number; qty: number }

export default function Basket() {
  const [lines, setLines] = useState<Line[]>([
    { name: 'Rice, 5 kg', price: 9500, qty: 1 },
    { name: 'Palm oil, 1 l', price: 2600, qty: 2 },
  ])
  const [total, setTotal] = useState(0)

  useEffect(() => {
    setTotal(lines.reduce((sum, line) => sum + line.price * line.qty, 0))
  }, [lines])

  function addOne(name: string) {
    setLines(lines.map((line) =>
      line.name === name ? { ...line, qty: line.qty + 1 } : line,
    ))
  }

  return (
    <section>
      <h2>Basket</h2>
      <ul>
        {lines.map((line) => (
          <li key={line.name}>
            {line.name} × {line.qty}{' '}
            <button onClick={() => addOne(line.name)}>Add one</button>
          </li>
        ))}
      </ul>
      <p data-testid="total">Total: ₦{total.toLocaleString('en-NG')}</p>
    </section>
  )
}
TSX
npm run lint

The linter warns react(set-state-in-effect) on the setTotal line. The warning is right. Every time lines changes, React renders the basket with the old total, commits that to the screen, runs the effect, and renders again with the new one. That is two renders for one click, a total that is briefly wrong, and a second copy of information that can drift from the first.

Calculate it during render instead. Replace the file:

Bash
cat > src/Basket.tsx <<'TSX'
import { useState } from 'react'

type Line = { name: string; price: number; qty: number }

export default function Basket() {
  const [lines, setLines] = useState<Line[]>([
    { name: 'Rice, 5 kg', price: 9500, qty: 1 },
    { name: 'Palm oil, 1 l', price: 2600, qty: 2 },
  ])

  const itemCount = lines.reduce((sum, line) => sum + line.qty, 0)
  const total = lines.reduce((sum, line) => sum + line.price * line.qty, 0)

  function addOne(name: string) {
    setLines(lines.map((line) =>
      line.name === name ? { ...line, qty: line.qty + 1 } : line,
    ))
  }

  return (
    <section>
      <h2>Basket</h2>
      <ul>
        {lines.map((line) => (
          <li key={line.name}>
            {line.name} × {line.qty}{' '}
            <button onClick={() => addOne(line.name)}>Add one</button>
          </li>
        ))}
      </ul>
      <p data-testid="total">
        {itemCount} items, ₦{total.toLocaleString('en-NG')}
      </p>
    </section>
  )
}
TSX
cat > src/App.tsx <<'TSX'
import WindowWidth from './WindowWidth'
import Clock from './Clock'
import RateTicker from './RateTicker'
import MemberCard from './MemberCard'
import Basket from './Basket'

export default function App() {
  return (
    <main>
      <h1>Effects lab</h1>
      <WindowWidth />
      <Clock />
      <RateTicker />
      <MemberCard />
      <Basket />
    </main>
  )
}
TSX
npm run lint

Adding the item count cost one line and no state. The rule: if a value can be computed from props and state, compute it. Only when a calculation is measurably slow, such as filtering thousands of rows on every keystroke, wrap it in useMemo, which still runs during render and never needs an effect.

Check it worked

The basket shows 3 items, ₦14,700. Click Add one next to the rice: the line reads Rice, 5 kg × 2 and the total changes to 4 items, ₦24,200 in the same render. npm run lint no longer warns, and Basket.tsx does not import useEffect at all.

Step 6 · Reset state with a key instead of an effect

The second kind resets state when a prop changes. Here is a note editor that is reused for several contacts. A typical first attempt clears the draft in an effect:

TSX
function NoteEditor({ contactId, name }: { contactId: number; name: string }) {
  const [draft, setDraft] = useState('')

  useEffect(() => {
    setDraft('')
  }, [contactId])
  // ...
}

It draws the new contact's name with the old contact's draft first and clears it a render later, and every piece of state added to the editor later needs its own line in that effect. React already has a way to say "this is a different thing now": the key. When a component's key changes, React throws away its state and starts it fresh. Create src/Notes.tsx:

Bash
cat > src/Notes.tsx <<'TSX'
import { useState } from 'react'

const contacts = [
  { id: 1, name: 'Amara' },
  { id: 2, name: 'Kwame' },
  { id: 3, name: 'Zainab' },
]

function NoteEditor({ name }: { name: string }) {
  const [draft, setDraft] = useState('')
  return (
    <label>
      Note for {name}
      <textarea value={draft} onChange={(event) => setDraft(event.target.value)} />
    </label>
  )
}

export default function Notes() {
  const [contactId, setContactId] = useState(1)
  const contact = contacts.find((c) => c.id === contactId)!

  return (
    <section>
      <h2>Notes</h2>
      {contacts.map((c) => (
        <button key={c.id} aria-pressed={c.id === contactId} onClick={() => setContactId(c.id)}>
          {c.name}
        </button>
      ))}
      <NoteEditor key={contact.id} name={contact.name} />
    </section>
  )
}
TSX
cat > src/App.tsx <<'TSX'
import WindowWidth from './WindowWidth'
import Clock from './Clock'
import RateTicker from './RateTicker'
import MemberCard from './MemberCard'
import Basket from './Basket'
import Notes from './Notes'

export default function App() {
  return (
    <main>
      <h1>Effects lab</h1>
      <WindowWidth />
      <Clock />
      <RateTicker />
      <MemberCard />
      <Basket />
      <Notes />
    </main>
  )
}
TSX

NoteEditor has no effect and does not even need the contact's ID. The parent decides identity by passing key={contact.id}. Any state you add to the editor later, such as a "saving" flag or a selected tag, resets along with the draft.

Check it worked

Type Call back on Monday in the box under "Note for Amara", then click Kwame. The label changes to "Note for Kwame" and the box is empty in the same frame, with no flash of Amara's text. Click Amara again: her draft is gone too, because her editor was discarded. If you want each contact to keep a draft, that is a different design: store the drafts in the parent as an object keyed by contact ID.

Step 7 · Move event logic out of an effect and into the handler

The third kind runs code because of something the user did, but runs it in an effect that watches a flag. Here is a waiting list button written that way:

TSX
const [joined, setJoined] = useState(loadJoined)
const [notice, setNotice] = useState('')

useEffect(() => {
  if (joined) {
    saveJoined()
    sendEvent('waitlist_joined')
    setNotice('Thanks. You are on the list.')
  }
}, [joined])

It works on the first click. But joined is restored from the browser's storage when the page loads, so on every later visit the effect sees true, sends the analytics event again and shows the thank-you message to someone who joined last week. The effect cannot tell "the user clicked" from "the page loaded in this state". The click handler can, because it only runs on a click. Create src/Waitlist.tsx with all three actions in the handler:

Bash
cat > src/Waitlist.tsx <<'TSX'
import { useState } from 'react'

function loadJoined() {
  try {
    return localStorage.getItem('waitlist') === 'joined'
  } catch {
    return false
  }
}

function saveJoined() {
  try {
    localStorage.setItem('waitlist', 'joined')
  } catch {
    // Storage can be blocked; the page still works without it.
  }
}

function sendEvent(name: string) {
  // Stands in for an analytics call.
  console.log(`analytics ${name}`)
}

export default function Waitlist() {
  const [joined, setJoined] = useState(loadJoined)
  const [notice, setNotice] = useState('')

  function join() {
    setJoined(true)
    saveJoined()
    sendEvent('waitlist_joined')
    setNotice('Thanks. You are on the list.')
  }

  return (
    <section>
      <h2>Waiting list</h2>
      <button onClick={join} disabled={joined}>
        {joined ? 'On the list' : 'Join the waiting list'}
      </button>
      <p role="status" data-testid="notice">{notice}</p>
    </section>
  )
}
TSX
cat > src/App.tsx <<'TSX'
import WindowWidth from './WindowWidth'
import Clock from './Clock'
import RateTicker from './RateTicker'
import MemberCard from './MemberCard'
import Basket from './Basket'
import Notes from './Notes'
import Waitlist from './Waitlist'

export default function App() {
  return (
    <main>
      <h1>Effects lab</h1>
      <WindowWidth />
      <Clock />
      <RateTicker />
      <MemberCard />
      <Basket />
      <Notes />
      <Waitlist />
    </main>
  )
}
TSX
npx tsc -b
npm run lint

Ask one question of any effect: does this code run because the component is on screen, or because of a particular interaction? Being on screen means an effect, as with the feed connection. A particular interaction means the handler for it. useState(loadJoined) passes the function itself, so React reads storage once on the first render rather than on every render.

Check it worked

npx tsc -b prints nothing and npm run lint reports no warnings. Click Join the waiting list: the message "Thanks. You are on the list." appears and the console logs analytics waitlist_joined once, even under StrictMode, because React does not double-run event handlers. Reload the page: the button reads "On the list" and is disabled, there is no message and no new analytics line. To start over, run localStorage.removeItem('waitlist') in the console and reload.

Step 8 · Build for production and tidy up

Count what is left. Three effects remain, in WindowWidth, Clock and RateTicker, plus the fetch in MemberCard, and each one connects to something outside React and cleans up after itself. Every other piece of logic runs during render or in a handler.

Stop the dev server with Ctrl+C in its terminal, then build and preview the production version:

Bash
npm run build
Bash
npm run preview

Open http://localhost:4173/ with the Console tab open, then stop the preview with Ctrl+C when you are done. Delete the project when you no longer need it:

Bash
cd ~
rm -rf ~/effects-lab

Check it worked

npm run build ends with built in and a time. In the preview, the console shows connect USD/NGN exactly once: no disconnect and reconnect, because StrictMode's extra cycle only happens in development. Everything else on the page behaves as it did in the dev server.

Next steps

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Platform Engineering

Get new tutorials

New tutorials, about twice a month.