Skip to content

Fix rehydration race condition with async drivers (e.g. IndexedDB) - #23

Closed
caspg wants to merge 1 commit into
zewish:masterfrom
caspg:master
Closed

caspg wants to merge 1 commit into
zewish:masterfrom
caspg:master

Conversation

@caspg

@caspg caspg commented Feb 17, 2026

Copy link
Copy Markdown

When using an async storage driver (like IndexedDB), the rehydrate function calls store.getState() before awaiting the storage load. If any actions are dispatched while the load is in-flight (e.g. RTK Query registering endpoints, middleware running), those state changes get overwritten when the rehydrated state is dispatched.

There's a related issue in rememberReducer — the REMEMBER_REHYDRATED case spreads data.state (a snapshot captured at @@INIT time) instead of the current state parameter.

…sync load

  Move store.getState() after the async driver load in rehydrate() so the
  snapshot reflects state changes (e.g. RTK Query fulfillments) that occurred
  while IndexedDB was loading. Also use current reducer state instead of
  initial state as the merge base in REMEMBER_REHYDRATED handler.
Repository owner deleted a comment from codecov-commenter Feb 18, 2026
switch (action.type) {
case REMEMBER_REHYDRATED: {
const rehydratedState = {
...data.state,

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm 99% sure this one is something we don't want to do, since it would break the loading of the initial reducer values.

@zewish

zewish commented Feb 18, 2026 •

Copy link
Copy Markdown
Owner

Hey @caspg, thank you for taking the time to open a PR.

  1. The fix to the rehydrate function seems legit to me since there is a theoretical race condition there - it is probably very rare, but still. Ideally I'd like to see a minimal reproduction repo where you actually hit this issue.
  2. I don't think that the change to the rememberReducer function is correct though, since it would break the loading of the initial values in some cases. I think you might be missing the point there - during the @@INIT call the data.state captures the initial state that gets replaced with the actual state + the rehydrated state once the state is rehydrated.

That said, I would gladly merge the rehydrate fix in case you revert the changes you made to rememberReducer and add a unit testing specifically for the race condition you mentioned (e.g. using vi.useFakeTimers() or similar).

@zewish

zewish commented May 14, 2026

Copy link
Copy Markdown
Owner

Closing due to inactivity - feel free to reopen if you'd like to continue the discussion.

@zewish zewish closed this May 14, 2026
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