Skip to content
This repository was archived by the owner on Apr 26, 2026. It is now read-only.

perf(hooks): extract restorePurchases into useCallback for stable reference#3172

Merged
hyochan merged 2 commits into
mainfrom
improvement/restore-purchases-usecallback
Mar 25, 2026
Merged

perf(hooks): extract restorePurchases into useCallback for stable reference#3172
hyochan merged 2 commits into
mainfrom
improvement/restore-purchases-usecallback

Conversation

@hyochan

@hyochan hyochan commented Mar 25, 2026

Copy link
Copy Markdown
Owner

Summary

Extracts the inline restorePurchases function from the useIAP hook's return statement into a properly memoized useCallback.

Problem

All other public functions returned by useIAP (e.g. finishTransaction, requestPurchase, fetchProducts, validateReceipt) are wrapped in useCallback to provide a stable reference across renders. However, restorePurchases was defined as an inline async () => {} directly in the return statement, causing it to be recreated on every render.

This inconsistency means:

  • Components that receive restorePurchases as a prop and use it in a useEffect or useCallback dependency array will trigger unnecessary re-runs
  • Strict mode linting (e.g. react-hooks/exhaustive-deps) can flag its usage since it's not stable
  • It's inconsistent with the rest of the hook's API surface

Changes

  • Extracted restorePurchases into a useCallback with appropriate dependencies [getAvailablePurchasesInternal, invokeOnError]
  • Removed the now-outdated comment // No local restorePurchases; use the top-level helper via returned API
  • The return statement now references the stable restorePurchases variable

Why

Improves performance consistency and aligns restorePurchases with the rest of the hook's API design.

Summary by CodeRabbit

  • Refactor
    • Updated restore flow: on iOS the app now performs a platform sync before refreshing purchases. No change to public API or expected behavior for end users.
  • Tests
    • Test suite updated to reflect the new iOS restore sequence and error propagation scenarios.

@gemini-code-assist

Copy link
Copy Markdown
Contributor

Summary of Changes

Hello, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request addresses a performance and consistency issue within the useIAP React hook. Previously, the restorePurchases function was defined inline, causing it to be recreated on every render, unlike other stable functions provided by the hook. By wrapping restorePurchases in useCallback, the change ensures a stable function reference, preventing unnecessary re-renders in consuming components and aligning its behavior with the rest of the hook's API.

Highlights

  • Performance Improvement: The restorePurchases function within the useIAP hook was extracted into a useCallback to ensure a stable reference across renders, resolving an inconsistency with other public functions returned by the hook.

🧠 New Feature in Public Preview: You can now enable Memory to help Gemini Code Assist learn from your team's feedback. This makes future code reviews more consistent and personalized to your project's style. Click here to enable Memory in your admin console.

Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for GitHub and other Google products, sign up here.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

@coderabbitai

coderabbitai Bot commented Mar 25, 2026

Copy link
Copy Markdown

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 452bf9fc-68ff-45ac-9704-cecf233fd449

📥 Commits

Reviewing files that changed from the base of the PR and between b13c5b8 and af4312b.

📒 Files selected for processing (2)
  • src/__tests__/hooks/useIAP.test.ts
  • src/hooks/useIAP.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/hooks/useIAP.ts

📝 Walkthrough

Walkthrough

Refactored restorePurchases in the useIAP hook into a useCallback-memoized function and changed iOS restore behavior to call IAP.syncIOS() before refreshing purchases via getAvailablePurchasesInternal(). Error handling still logs a warning and forwards errors to invokeOnError.

Changes

Cohort / File(s) Summary
useIAP Hook
src/hooks/useIAP.ts
Refactored restorePurchases to a useCallback-memoized function and on iOS now calls IAP.syncIOS() before invoking getAvailablePurchasesInternal(). Error logging and invokeOnError propagation remain.
Tests — useIAP
src/__tests__/hooks/useIAP.test.ts
Updated tests to mock/assert IAP.syncIOS() behavior on iOS, added cases for syncIOS rejection and for getAvailablePurchases rejection during restore; verifies syncIOS is invoked and errors are forwarded to onError.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

Suggested labels

🪝 hooks, 🛠 refactor

Poem

🐰 I hopped into code with a curious twitch,
Wrapped a restore in a tidy little stitch.
On iOS I call sync before I peep,
Errors I warn, then softly keep.
A carrot for tests — they passed in a twitch! 🥕

🚥 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: extracting restorePurchases into a useCallback for memoization, which is the primary refactoring objective.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.

✏️ 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 improvement/restore-purchases-usecallback

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.

@codecov

codecov Bot commented Mar 25, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 68.97%. Comparing base (4d9f743) to head (af4312b).
⚠️ Report is 9 commits behind head on main.

Additional details and impacted files

Impacted file tree graph

@@            Coverage Diff             @@
##             main    #3172      +/-   ##
==========================================
+ Coverage   68.90%   68.97%   +0.07%     
==========================================
  Files           9        9              
  Lines        1791     1792       +1     
  Branches      584      585       +1     
==========================================
+ Hits         1234     1236       +2     
+ Misses        552      551       -1     
  Partials        5        5              
Flag Coverage Δ
library 68.97% <100.00%> (+0.07%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

Files with missing lines Coverage Δ
src/hooks/useIAP.ts 70.45% <100.00%> (+0.74%) ⬆️
🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@gemini-code-assist gemini-code-assist 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.

Code Review

This pull request refactors the restorePurchases function within the useIAP hook by extracting its logic into a memoized useCallback hook. The reviewer has identified a potential redundancy in the restorePurchases implementation, noting that restorePurchasesTopLevel already calls getAvailablePurchases, making the subsequent call to getAvailablePurchasesInternal potentially redundant. An optimization is suggested to avoid duplicate network requests, particularly for iOS by using syncIOS directly.

Comment thread src/hooks/useIAP.ts
@hyochan hyochan added the 🍗 enhancement New feature or request label Mar 25, 2026
…Purchases

Call syncIOS directly instead of restorePurchasesTopLevel to avoid
double network request, since getAvailablePurchasesInternal already
fetches available purchases afterward.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
@hyochan hyochan merged commit 1bbbbae into main Mar 25, 2026
9 checks passed
@hyochan hyochan deleted the improvement/restore-purchases-usecallback branch March 25, 2026 07:45
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

🍗 enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant