Skip to content

fix: optimize session handling in useLocalizationConfig - #3256

Merged
eduardoformiga merged 3 commits into
canary-v2from
fix/race-condition-use-localization-config
Apr 1, 2026
Merged

eduardoformiga merged 3 commits into
canary-v2from
fix/race-condition-use-localization-config

Conversation

@eduardoformiga

@eduardoformiga eduardoformiga commented Apr 1, 2026 •

Copy link
Copy Markdown
Member

What's the purpose of this pull request?

Fix the race condition in the useLocalizationConfig hook that causes the empty cart after refreshing the page or browsing to another page.

How it works?

  • Replaced state management for session with a ref to prevent unnecessary re-renders.
  • Updated the effect dependencies to only react to settings changes, improving performance.
  • Added logic to handle session updates without triggering re-renders, ensuring smoother localization updates.

Summary by CodeRabbit

  • Refactor
    • Reduced unnecessary UI re-renders by changing how localization session state is tracked and observed.
    • Added a first-mount guard and streamlined session→settings synchronization to avoid redundant updates while keeping settings aligned with explicit locale bindings.

…onfig

- Replaced state management for session with a ref to prevent unnecessary re-renders.
- Updated the effect dependencies to only react to settings changes, improving performance.
- Added logic to handle session updates without triggering re-renders, ensuring smoother localization updates.
@eduardoformiga
eduardoformiga requested a review from a team as a code owner April 1, 2026 17:01
@eduardoformiga
eduardoformiga requested review from ommeirelles and renatamottam and removed request for a team April 1, 2026 17:01
@coderabbitai

coderabbitai Bot commented Apr 1, 2026 •

Copy link
Copy Markdown
Contributor

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 3098ac05-4695-4c68-be44-3580488acd67

📥 Commits

Reviewing files that changed from the base of the PR and between 472d0ab and f8e5989.

📒 Files selected for processing (1)
  • packages/core/src/sdk/localization/useLocalizationConfig.tsx

Walkthrough

useLocalizationConfig no longer mirrors sessionStore into React state. It writes session updates to a mutable ref via sessionStore.subscribe, avoids re-renders, changes the session→settings sync to depend only on settings, and adds a first-mount guard that skips initial alignment unless a URL locale binding matches.

Changes

Cohort / File(s) Summary
Localization Config Hook
packages/core/src/sdk/localization/useLocalizationConfig.tsx
Removed React session state and setSession; subscribe writes to sessionRef.current to prevent re-renders. Effect dependencies reduced to [settings], reads session from ref at execution, and adds isFirstMount guard to skip initial sync unless URL locale binding matches. (+24/-6 lines)

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

Suggested labels

enhancement

Suggested reviewers

  • renatamottam
  • gabpaladino

Poem

A ref keeps whispers soft and still,
No extra renders bend the will.
First mount checks the URL's song,
Syncs only if the match is strong. 🎉

🚥 Pre-merge checks | ✅ 3
✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately describes the main change: optimizing session handling by replacing state management with a ref to prevent re-renders—directly addressing the race condition mentioned in PR objectives.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/race-condition-use-localization-config

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@codesandbox-ci

codesandbox-ci Bot commented Apr 1, 2026 •

Copy link
Copy Markdown

This pull request is automatically built and testable in CodeSandbox.

To see build info of the built libraries, click here or the icon next to each commit SHA.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@packages/core/src/sdk/localization/useLocalizationConfig.tsx`:
- Around line 47-50: The isFirstMount.current guard in useLocalizationConfig
prevents syncing the initial session when the URL-derived settings differ from
the persisted session; change the logic so the first-mount path still performs a
sync when settings !== sessionRef.current (compare locale/currency/channel from
settings to sessionRef.current) instead of simply returning—either remove the
early return or replace it with a conditional that updates sessionRef.current
and triggers the existing sync logic (refer to isFirstMount,
useLocalizationConfig, settings, sessionRef.current).
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 4906a170-ec1d-4f9e-bb68-b786e9c8d76a

📥 Commits

Reviewing files that changed from the base of the PR and between b611c7c and 991e17f.

📒 Files selected for processing (1)
  • packages/core/src/sdk/localization/useLocalizationConfig.tsx

…calizationConfig

- Added checks to prevent unnecessary updates when session settings match current localization settings.
- Improved session handling by ensuring that the session reference is consistently used, optimizing performance during the first mount.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@packages/core/src/sdk/localization/useLocalizationConfig.tsx`:
- Around line 40-44: The subscription in useLocalizationConfig's useEffect
currently only updates sessionRef.current and has no dependency on external
session changes, so add a minimal selector/version check inside the
sessionStore.subscribe callback to detect changes to session.locale,
session.currency, or session.channel.salesChannel and trigger the reconciliation
logic when those values differ; specifically, inside the existing
sessionStore.subscribe callback (where sessionRef.current is set) compute a
compact key or version from session.locale + session.currency +
session.channel?.salesChannel, compare it to a stored ref (e.g.,
sessionVersionRef), update that ref when it differs, and then call the existing
reconciliation/update code that derives settings so the hook re-syncs only when
those three fields change while retaining the performance win of not subscribing
to the whole session object.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 8bd6d942-45ec-4ff9-ae8a-db7b0006e29d

📥 Commits

Reviewing files that changed from the base of the PR and between 991e17f and 472d0ab.

📒 Files selected for processing (1)
  • packages/core/src/sdk/localization/useLocalizationConfig.tsx

Comment on lines 40 to 44
useEffect(() => {
return sessionStore.subscribe((newSession) => {
setSession(newSession)
sessionRef.current = newSession
})
}, [])

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

Keep reacting to external localization mutations.

With session removed from the dependency chain, this hook no longer re-synchronizes when some other flow updates session.locale, session.currency, or channel.salesChannel. The subscription only mutates sessionRef.current, so the route-derived settings and session can stay diverged until the next settings change.

Please keep the perf win, but re-trigger reconciliation when those three session fields change externally (for example via a small selector/version in the subscription rather than mirroring the whole session back into state).

Also applies to: 46-82

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/core/src/sdk/localization/useLocalizationConfig.tsx` around lines 40
- 44, The subscription in useLocalizationConfig's useEffect currently only
updates sessionRef.current and has no dependency on external session changes, so
add a minimal selector/version check inside the sessionStore.subscribe callback
to detect changes to session.locale, session.currency, or
session.channel.salesChannel and trigger the reconciliation logic when those
values differ; specifically, inside the existing sessionStore.subscribe callback
(where sessionRef.current is set) compute a compact key or version from
session.locale + session.currency + session.channel?.salesChannel, compare it to
a stored ref (e.g., sessionVersionRef), update that ref when it differs, and
then call the existing reconciliation/update code that derives settings so the
hook re-syncs only when those three fields change while retaining the
performance win of not subscribing to the whole session object.

…seLocalizationConfig

- Enhanced the first mount logic to prevent unnecessary session updates when no URL binding matches.
- Ensured consistent use of session reference for improved performance and reliability during localization updates.
@eduardoformiga
eduardoformiga removed the request for review from renatamottam April 1, 2026 18:43
@eduardoformiga
eduardoformiga merged commit 6d4e6df into canary-v2 Apr 1, 2026
3 checks passed
@eduardoformiga
eduardoformiga deleted the fix/race-condition-use-localization-config branch April 1, 2026 20:04
@eduardoformiga
eduardoformiga restored the fix/race-condition-use-localization-config branch April 1, 2026 20:04
eduardoformiga added a commit that referenced this pull request Apr 1, 2026
eduardoformiga added a commit that referenced this pull request Apr 1, 2026
#3256)" (#3257)

This reverts commit 6d4e6df.

## What's the purpose of this pull request?

<!--- Considering the context, what is the problem we'll solve? Where in
VTEX's big picture our issue fits in? Write a tweet about the context
and the problem itself. --->

## How it works?

<!--- Tell us the role of the new feature, or component, in its context.
Provide details about what you have implemented and screenshots if
applicable. --->

## How to test it?

<!--- Describe the steps with bullet points. Is there any external link
that can be used to better test it or an example? --->

### Starters Deploy Preview

<!--- Add a link to a deploy preview from `starter.store` with this
branch being used. --->

<!--- Tip: You can get an installable version of this branch from the
CodeSandbox generated when this PR is created. --->

## References

<!--- Spread the knowledge: is there any content you used to create this
PR that is worth sharing? --->

<!--- Extra tip: adding references to related issues or mentioning
people important to this PR may be good for the documentation and
reviewing process --->

## Checklist

<em>You may erase this after checking them all 😉</em>

**PR Title and Commit Messages**

- [ ] PR title and commit messages follow the [Conventional
Commits](https://www.conventionalcommits.org/en/v1.0.0/) specification
- Available prefixes: `feat`, `fix`, `chore`, `docs`, `style`,
`refactor`, `ci` and `test`

**PR Description**

- [ ] Added a label according to the PR goal - `breaking change`, `bug`,
`contributing`, `performance`, `documentation`..

**Dependencies**

- [ ] Committed the `pnpm-lock.yaml` file when there were changes to the
packages

**Documentation**

- [ ] PR description
- [ ] For documentation changes, ping `@Mariana-Caetano` to review and
update (Or submit a doc request)
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.

1 participant