electric-sql / electric-sql/electric

Feature request: Automatically clean up shape streams on params change or unmount

Open
#2,788 4 comments 7 reactions 0 assignees View on GitHub
feature request triage
Dominant language
TypeScript
Stars
10.4k
Forks
375
Avg merge
3d 1h
Merged PRs (30d)
18

Description

**Is your feature request related to a problem? Please describe.**

The current behavior of the `useShape` hook is to leave the underlying shape stream open when shape params change or the hook unmounts. In SPA:s or cases where params are dynamic, this leads to a compounding effect where more and more "zombie" shape streams accumulate. In the product I'm building this can quickly add up to hundreds of shape streams.

The [documented solution](https://electric-sql.com/docs/integrations/react#how-to-abort-a-shape-subscription-%E2%80%94-abortcontroller) of using an `AbortController` provide a way to counter this issue but I've found a couple of drawbacks:

1. It doesn't work well in React's strict mode due to way `useShape` caches shape streams. It uses serialized `options` as the the cache key with `signal` being serialized as `{}`. The cache doesn't react to changes in the `signal` option, e.g. a new `AbortController` instance. This means that if we loose track of the initial `AbortController` instance (which will happen in strict mode as [state initializers run twice](https://react.dev/reference/react/useState#my-initializer-or-updater-function-runs-twice)), we have no way of aborting the shape stream.
1. If a shape stream is used by multiple components, cancelling one will cancel all of them.
1. Juggling abort controllers add boilerplate, it would be nice if this was handled internally by `useShape`.

**Describe the solution you'd like**

In the docs you mention that you "plan to add a better API for unsubscribing from updates & cleaning up shapes that are no longer needed". This is exactly what I'm in need of.

I would like `useShape` to automatically react to unmounts or changes in `params` and unsubscribe from the underlying shape stream accordingly. I would also like shape streams without subscribers to be automatically cancelled or paused, and resumed when subscribed to again.

**Additional context**

I'm using `@electric-sql/react@1.0.4` with `react@19.0.0` and `next@15.3.2`.

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.