Skip to content

feat: rehydrate lazy-loaded reducers on demand (store.rehydrate) - #28

Open
KAMRONBEK wants to merge 3 commits into
zewish:masterfrom
KAMRONBEK:docs/lazy-loaded-reducers
Open

KAMRONBEK wants to merge 3 commits into
zewish:masterfrom
KAMRONBEK:docs/lazy-loaded-reducers

Conversation

@KAMRONBEK

@KAMRONBEK KAMRONBEK commented Jul 17, 2026 •

Copy link
Copy Markdown

Adds first-class support for lazy-loaded / injected reducers via a new store.rehydrate(keys?) method. Addresses #26.

In #26 the concern was that injecting a persisted slice races the one-time rehydration: rehydrate() fires once at init, so a reducer injected later misses its stored value and starts from its initial state. This adds an explicit, opt-in way to load it after injection:

rootReducer.inject(lazyPersistedSlice);   // add the reducer
await store.rehydrate(['lazyPersisted']); // load its persisted state + keep persisting it
  • store.rehydrate(keys) reads those keys from storage, dispatches REMEMBER_REHYDRATED, and adds them to the remembered set so they persist from then on. With no arguments it re-reads every currently remembered key.
  • Non-persisted injected slices already worked (they just aren't in rememberedKeys); that case is documented too.

Changes:

  • index.ts — attach store.rehydrate (reuses the existing internal rehydrate); the enhancer returns Object.assign(store, { rehydrate }).
  • types.ts — RehydrateFunction + RememberEnhancerStoreExt, set as the enhancer's default Ext so store.rehydrate is typed without extra generics.
  • tests — 3 new cases in index.test.ts; full suite 7812 pass, index.ts 100% covered; typecheck + lint clean.
  • docs — usage/lazy-loaded-reducers documents both cases and is linked in the sidebar.

Verified end-to-end against a real store + async driver: inject a slice, call store.rehydrate([key]), and it loads the persisted value; without the call it stays at its default (the race described in the issue).

A couple of things I'd defer to you:

  • naming (store.rehydrate vs something more scoped), and whether you'd rather it be opt-in behind an option instead of always attached.
  • the on-demand path currently reuses your migrate (identity by default). Happy to skip migrate on store.rehydrate if you'd prefer it only run at init.

I know lazy slices weren't on the roadmap, so if you'd rather not add API surface I'm glad to trim this back to just the docs page.

Adds store.rehydrate(keys?) so an injected/persisted reducer can be loaded
from storage after the store is created. Without it, a reducer injected after
init misses its one-time rehydration and its stored value is dropped.

- index.ts: attach store.rehydrate; it reads the given keys, dispatches
  REMEMBER_REHYDRATED, and adds them to the remembered set so they persist.
- types.ts: RehydrateFunction + RememberEnhancerStoreExt (default enhancer Ext),
  so store.rehydrate is typed without extra generics.
- tests: 3 new cases; full suite 7812 pass, index.ts 100% covered.
- docs: usage/lazy-loaded-reducers documents the API for both cases.
@KAMRONBEK KAMRONBEK changed the title docs: document lazy-loaded (injected) reducers feat: rehydrate lazy-loaded reducers on demand (store.rehydrate) Jul 17, 2026
@zewish

zewish commented Sep 8, 2026 •

Copy link
Copy Markdown
Owner

Hey @KAMRONBEK, thank you for this PR! What you're suggesting is introducing a new unsafe API, without marking it as such. My feeling is we could still do this, because apparently there is a valid use-case, but I'd have to think more how the actual API for this should look for this, considering the fact we might want to handle more use-cases than the injected reducer one.

…rate()

Addresses review feedback that this introduced an unsafe API without
marking it as such.

Renames store.rehydrate() to store.unsafeRehydrate(), and fixes four
timing defects that made the old implementation genuinely unsafe rather
than merely unconventional:

- Read the state after the storage read, in the same tick as the
  dispatch. It was captured before the await, so REMEMBER_REHYDRATED
  re-broadcast a stale snapshot and silently reverted anything dispatched
  while storage was being read. This also made concurrent calls revert
  each other.
- Only add keys to the remembered set once their stored value has been
  loaded. Adding them up front let the persist subscriber write the
  slice's initial state over good stored data mid-read - and the
  in-flight read then returned that clobbered value, losing it for good.
- Do not add keys, or dispatch, when the read fails. A transient storage
  error otherwise started persisting the slice's initial state.
- Do not re-apply migrate(). It is a whole-state, run-once function;
  re-running it over already-migrated state is unsound.

Also stops mutating the rememberedKeys array the caller passed in: the
store keeps its own copy, shared with init() so newly remembered keys
are still persisted.

Adds an end-to-end suite covering these guarantees against a real store
and a real async driver - they are all timing properties that a mocked
driver cannot express.
@KAMRONBEK

Copy link
Copy Markdown
Author

Thanks for looking, and fair call — you were right that it was unsafe, more specifically than I'd realised. Digging in, the old implementation had four real timing defects, not just an unlabelled API:

  1. rehydrate() captures store.getState() before await load(...), and rememberReducer handles REMEMBER_REHYDRATED as {...data.state, ...action.payload}, ignoring the incoming state. At init that's harmless. Called at runtime it re-broadcasts a pre-read snapshot, so anything dispatched while storage is being read gets silently reverted — and the same cause made two concurrent calls revert each other.
  2. Keys were added to rememberedKeys before the read finished, so the persist subscriber could write the slice's initial state over its stored value mid-read — and the in-flight read then returned that clobbered value. That one is real data loss, with a ~50ms window on AsyncStorage/IndexedDB.
  3. A failed read still added the keys, so a transient storage error started persisting initial state over good data.
  4. migrate re-ran over the whole state on every call.

It also mutated the rememberedKeys array the caller passed in — my own test asserted that, which should have been a hint.

I've pushed a commit that closes all of it and renames the method to store.unsafeRehydrate(): state is re-read after the load in the same tick as the dispatch; keys join the remembered set only once their value has loaded; a failed read reports to errorHandler and does nothing else; migrate isn't re-applied; and the store keeps its own copy of the keys array. REMEMBER_REHYDRATED's payload shape is unchanged, though I did amend the actions page since "dispatched once" isn't strictly true if you use this.

7829 tests pass, 100% coverage, lint/typecheck clean, docs build. The new unsafe-rehydrate.test.ts drives a real store and a real async driver — 6 of its 9 cases fail against the previous version of this PR, which is rather the point. It's a different style from the rest of the suite (no mocks); happy to fold it into the mocked tests if you'd prefer one style.

One caveat I couldn't close: with initActionType set, Redux Remember is disabled until that action fires, so there's no in-flight initialisation to wait on and a later init would overwrite an on-demand load. That's documented rather than fixed.

On wanting to cover more than the injected-reducer case — agreed, and I think a keyed rehydrate is the primitive underneath most of them: cross-tab sync (storage event → re-read that key), user switch / logout (re-read everything, or drop keys), manual refresh, and un-injecting a slice (which needs the inverse — removing a key). So the real question is whether the remembered set should be mutable at all, and if so whether the surface is one method or a pair. Three shapes, your call:

a. what's there now — store.unsafeRehydrate(keys?) and nothing else
b. same, but only attached when opted into (rememberEnhancer(driver, keys, { unsafeRehydrate: true })), so stores that don't ask for it don't get it, and the type only widens when enabled
c. a properly mutable remembered set — unsafeRehydrate(keys?) plus unsafeForget(keys) — covering logout and un-injecting too, at the cost of more surface

I'd lean b: it keeps this PR narrow, makes "unsafe" a deliberate setup-time choice rather than something every store is handed, and leaves c open later without a breaking change. The branch currently implements a. Happy to build c up front if you'd rather design it once — and if you'd rather not add the API at all, I'll cut this back to just the docs page for the non-persisted case, which stands on its own.

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants