Skip to content

This notebook belongs to

Sadat Jubayer

Senior Software Engineer at Premio

If found, please return to hello@jubayer.dev

Vol. 7Seven years of building

Started
January 2020
Everyday tools
TypeScript, Vue, React, Next.js, NestJS, React Native
Education
B.Sc. CSSE, AIUB, 2020
2 min readReact

Write effects that survive Strict Mode double-run

Return a cleanup function so a subscription survives Strict Mode's extra development setup cycle.

Wrap the root of your app in <StrictMode> and React runs an extra effect setup and cleanup cycle in development. If your effect subscribes without cleaning up, both subscriptions remain active. Return an unsubscribe function from the effect to remove one before the next setup.

This example uses a fake store whose listeners.size counts live subscribers. Mount <StrictMode><Leaky /></StrictMode> with createRoot and check the count after React flushes the effects.

import { useEffect } from 'react'

const listeners = new Set<() => void>()
const store = {
  subscribe(fn: () => void) {
    listeners.add(fn)
    return () => listeners.delete(fn)
  },
}

function Leaky() {
  useEffect(() => {
    console.log('setup')
    store.subscribe(() => {})
  }, [])
  return null
}
// development: setup, setup
// subscribers after mount: 2
// subscribers after unmount: 2

In development the setup ran twice, and both subscribers were still there after the component unmounted. The effect returns nothing, so no code ever removes them.

Setup, cleanup, setup

Replace Leaky with Clean in the same root and use a fresh store for the comparison.

function Clean() {
  useEffect(() => {
    console.log('setup')
    const unsubscribe = store.subscribe(() => {})
    return () => {
      console.log('cleanup')
      unsubscribe()
    }
  }, [])
  return null
}
// development: setup, cleanup, setup
// subscribers after mount: 1
// subscribers after unmount: 0

React calls setup, cleanup and setup. Clean leaves one subscriber after mount and zero after unmount. React 19 skips the extra initial effect cycle when Strict Mode wraps only a subtree.

What happens in production

In a production build, React skips the extra Strict Mode cycle. On mount, each example logs setup once. Clean logs cleanup when you unmount it.

Leaky still ended with one subscriber after unmount in that build, so the unmounted component left its subscriber behind. In development, StrictMode doubles that count, which is how you notice it.

Write the cleanup as the undo

For each thing the setup creates, the cleanup removes it. A subscription gets an unsubscribe, an event listener gets removeEventListener, and a timer gets clearInterval. Check what remains after mount and again after unmount.

A ref guard that skips the second setup hides the leak during development. The subscription still survives unmount in production.