Skip to content

fix(useStorageValue): compose updates before rerender - #1721

Open
sridharkalaibala wants to merge 1 commit into
react-hookz:masterfrom
sridharkalaibala:pr/fix-1507
Open

sridharkalaibala wants to merge 1 commit into
react-hookz:masterfrom
sridharkalaibala:pr/fix-1507

Conversation

@sridharkalaibala

Copy link
Copy Markdown

What is the current behavior, and the steps to reproduce the issue?

Three consecutive functional increments from a stored/default value of 0 all receive 0 and leave the value at 1. The same stale value can be used when two mounted hooks update the same storage key before React renders.

Closes #1507.

What is the expected behavior?

Each functional update should receive the latest accepted value. Three increments should receive 0, 1 and 2 and leave both storage and the rendered value at 3.

How does this PR fix the problem?

Keep the current-value ref synchronized when the hook accepts a parsed storage notification or fetch result, together with the React state update. Previously, useSyncedRef refreshed that value only during a render. The shared implementation covers localStorage and sessionStorage and preserves the existing serialization, notification and stable-action behavior. A rejected serialization or failed write does not advance the value. Add JSDoc describing functional-update behavior.

This composes synchronous updates among mounted hooks in the same document; it does not introduce atomic read-modify-write across browser tabs.

Validation

  • Added 14 regression cases across actual jsdom localStorage and sessionStorage: consecutive increments, separate hook instances, removal, explicit fetch, rejected serialization, custom parsing, and failed writes.
  • All 14 fail against the original implementation and pass with this change.
  • Full DOM/SSR suite: 546 tests pass in 118 files.
  • Required yarn fmt, yarn lint:fix, yarn test, yarn build pass; final yarn fmt:check and yarn lint also pass.
  • Node 24.19.0, pinned Yarn 4.17.1, TypeScript 7.0.2. No native-browser or cross-tab atomicity claim.

Checklist

  • Have you read the contribution guideline?
  • Have you added an explanation of what your changes do and why you'd like us to include them?
  • Is there an existing issue for this PR? State updates in useLocalStorageValue are not queued like useState is. #1507
  • Have the files been linted and formatted?
  • Have the docs been updated to match the changes in the PR? Setter JSDoc.
  • Have the tests been updated to match the changes in the PR?
  • Have you run the tests locally to confirm they pass?

AI assistance: implemented and validated with OpenAI Codex.

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

Labels

None yet

Development

Successfully merging this pull request may close these issues.

State updates in useLocalStorageValue are not queued like useState is.

1 participant