Skip to content

Reading a computed atom without subscribing can prevent garbage collection #372

Description

@Sheraff

A computed atom can stay in memory after the application has finished using it. Reading it once with .get() is enough: its source keeps a reference to it, even if nothing ever subscribes to it.

This matters in React because a component can read an atom during render, then suspend before React subscribes. If that render is discarded, there is no subscription to clean up. Repeated abandoned renders can accumulate unused atoms and anything their getters capture.

Reproduction: @tanstack/store@0.11.1, Node 24.8.0, macOS. Save as repro.mjs and run node --expose-gc repro.mjs.

import { createAtom } from '@tanstack/store'

const source = createAtom(0)

function createAndDiscard() {
  const derived = createAtom(() => source.get() + 1)
  derived.get() // Read once; never subscribe.
  return new WeakRef(derived) // Observe it without keeping it alive.
}

const refs = Array.from({ length: 100 }, createAndDiscard)

// Give garbage collection several chances to release the unused atoms.
for (let i = 0; i < 10; i++) {
  await new Promise(resolve => setTimeout(resolve, 0))
  global.gc()
}

const remaining = refs.filter(ref => ref.deref() !== undefined).length
console.log(remaining) // Expected: 0. Actual: 100.
console.log(source.get()) // The source is still in use.

Removing derived.get() makes all 100 atoms collectible. Calling derived.subscribe(() => {}).unsubscribe() after the read also allows all 100 to be collected.

The cause appears to be the dependency tracking in atom.ts: reading the computed atom connects it to its source. Unsubscribing removes that connection, but an atom that was never subscribed has no corresponding cleanup.

Expected: once the application drops a computed atom, its source should not keep it alive solely because it was read earlier.

AI disclosure: This report was investigated, reproduced, and written by OpenAI Codex (AI), and filed at the user's request.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions