Skip to content

Conversation

@davemecha
Copy link
Owner

@davemecha davemecha commented Jul 18, 2025

Summary by CodeRabbit

  • New Features

    • Introduced a new experimental hook, useAsyncMemoSuspense, for memoizing asynchronous computations with React Suspense support.
    • Added documentation and usage examples for useAsyncMemoSuspense in the README.
  • Tests

    • Added comprehensive test suite for useAsyncMemoSuspense covering async/sync behavior, caching, dependency management, error handling, and concurrent features.
    • Improved existing tests for useAsyncMemo by ensuring mocks are reset before each test.
  • Documentation

    • Enhanced README with updated badge links, ESLint config examples, and detailed API reference for the new hook.
  • Chores

    • Updated package metadata for improved tree-shaking and test coverage configuration.
    • Upgraded ts-jest dependency for testing.
  • Refactor

    • Improved GitHub Actions workflow to conditionally run tests based on React version compatibility.

davemecha and others added 30 commits June 27, 2025 02:52
feat: add test suite with GitHub Actions workflow and React version compatibility tests
Adds JSDocs, README documentation, and tests for the new `useAsyncMemoSuspense` hook.

The documentation includes examples and important notes about SSR and client component usage.

The tests cover suspense, error handling, dependency changes, and scope usage.
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jul 18, 2025

Walkthrough

A new experimental React hook, useAsyncMemoSuspense, is introduced for async memoization with Suspense support, including its implementation, tests, documentation, and export. The test workflow is updated to conditionally exclude certain tests for older React versions. Additional minor updates are made to package metadata and test coverage configuration.

Changes

File(s) Change Summary
src/useAsyncMemoSuspense.ts New hook useAsyncMemoSuspense implemented for async memoization with Suspense and optional scoping.
src/tests/useAsyncMemoSuspense.test.tsx Comprehensive test suite added for useAsyncMemoSuspense, covering async, sync, error, cache, and dependency scenarios.
src/index.ts Export statement added for useAsyncMemoSuspense.
README.md Documentation for useAsyncMemoSuspense added, including usage, SSR notes, and ESLint config update.
.github/workflows/test.yml Test workflow split to conditionally exclude useAsyncMemoSuspense tests for React 16/17 using ignore patterns.
package.json Added sideEffects: false, upgraded ts-jest, and expanded Jest coverage exclusion.
src/tests/useAsyncMemo.test.ts Added jest.clearAllMocks() to test setup for consistent test isolation.

Sequence Diagram(s)

sequenceDiagram
  participant Component
  participant useAsyncMemoSuspense
  participant Cache
  participant Promise
  participant ReactSuspense

  Component->>useAsyncMemoSuspense: Call with factory, deps, options
  useAsyncMemoSuspense->>Cache: Check for cache entry (keyed by factory+deps+scope)
  alt Cache miss or deps changed
    useAsyncMemoSuspense->>Promise: Invoke async factory
    useAsyncMemoSuspense->>Cache: Store pending entry with promise
    useAsyncMemoSuspense-->>Component: throw Promise (suspends)
    Component->>ReactSuspense: Suspended until promise resolves
    Promise-->>Cache: Resolve or reject
    ReactSuspense->>Component: Resume rendering with result or error
  else Cache hit (success)
    useAsyncMemoSuspense-->>Component: Return cached value
  else Cache hit (error)
    useAsyncMemoSuspense-->>Component: throw cached error
  end
Loading

Possibly related PRs

  • davemecha/use-async-effekt#6: Introduces the same useAsyncMemoSuspense hook, including implementation, tests, and documentation.
  • davemecha/use-async-effekt#3: Modifies the GitHub Actions workflow for conditional test execution based on React version, closely related to the workflow changes here.
  • davemecha/use-async-effekt#4: Introduces the initial test workflow setup with React/Node matrix, which is further modified in this PR.

Poem

A rabbit with code in its paws,
Suspends for async without pause.
With caches and scopes,
And tests full of hopes,
Now React can memoize with applause!

(☁️🥕 await the carrot, then hop on!)


📜 Recent review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between d1c9956 and f2b6c19.

📒 Files selected for processing (1)
  • src/useAsyncMemoSuspense.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/useAsyncMemoSuspense.ts
✨ Finishing Touches
  • 📝 Generate Docstrings

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
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@codecov-commenter
Copy link

⚠️ Please install the 'codecov app svg image' to ensure uploads and comments are reliably processed by Codecov.

Codecov Report

Attention: Patch coverage is 84.00000% with 4 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
src/useAsyncMemoSuspense.ts 83.33% 1 Missing and 3 partials ⚠️

📢 Thoughts on this report? Let us know!

@coderabbitai coderabbitai bot changed the title Release v1.1.0: @coderabbitai Release v1.1.0: Add useAsyncMemoSuspense hook with implementation, tests, and documentation Jul 18, 2025
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (3)
.github/workflows/test.yml (1)

44-50: Consider improving the test exclusion strategy.

The conditional test execution is appropriate for React version compatibility, but the current implementation could be improved:

  1. The command on line 46 is complex and hard to maintain
  2. The regex pattern .*useAsyncMemoSuspense.* might be too broad
  3. Coverage exclusion is duplicated between the workflow and jest config

Consider these improvements:

-      - name: Run tests (excluding Suspense tests for React 16/17)
-        if: matrix.react-version == '16.8.0' || matrix.react-version == '17.0.0'
-        run: npm test -- --coverage --watchAll=false --testPathIgnorePatterns=".*useAsyncMemoSuspense.*" --collectCoverageFrom="src/**/*.ts" --collectCoverageFrom="!src/useAsyncMemoSuspense.ts"
+      - name: Run tests (excluding Suspense tests for React 16/17)
+        if: matrix.react-version == '16.8.0' || matrix.react-version == '17.0.0'
+        run: npm test -- --coverage --watchAll=false --testPathIgnorePatterns="useAsyncMemoSuspense\.test\.(ts|tsx)$"

This approach:

  • Uses a more precise regex pattern
  • Removes coverage exclusion duplication (handled by jest config)
  • Simplifies the command line
README.md (1)

17-17: Consider more professional wording.

The "vibe coded" terminology might be too informal for a professional library documentation. Consider a more professional alternative.

-Note: Tests are vibe coded. Specific tests are added when bugs are reported.
+Note: Tests are behavior-driven. Additional tests are added when bugs are reported.
src/useAsyncMemoSuspense.ts (1)

12-18: Consider memory management for the global cache

The global cache can grow unbounded over time, potentially causing memory issues in long-running applications. Consider implementing a cache eviction strategy (LRU, TTL, or max size limit).

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between e5147d7 and d1c9956.

⛔ Files ignored due to path filters (1)
  • package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (7)
  • .github/workflows/test.yml (1 hunks)
  • README.md (4 hunks)
  • package.json (3 hunks)
  • src/__tests__/useAsyncMemo.test.ts (1 hunks)
  • src/__tests__/useAsyncMemoSuspense.test.tsx (1 hunks)
  • src/index.ts (1 hunks)
  • src/useAsyncMemoSuspense.ts (1 hunks)
🧰 Additional context used
🧠 Learnings (7)
📓 Common learnings
Learnt from: davemecha
PR: davemecha/use-async-effekt#3
File: src/__tests__/test-utils.ts:6-8
Timestamp: 2025-06-29T11:06:37.033Z
Learning: In matrix testing scenarios where different versions of testing libraries are dynamically installed (like @testing-library/react-hooks vs @testing-library/react across React versions), using `any` types may be necessary due to unstable type dependencies, rather than importing specific types that may not be available in all test configurations.
src/__tests__/useAsyncMemo.test.ts (1)
Learnt from: davemecha
PR: davemecha/use-async-effekt#3
File: src/__tests__/test-utils.ts:6-8
Timestamp: 2025-06-29T11:06:37.033Z
Learning: In matrix testing scenarios where different versions of testing libraries are dynamically installed (like @testing-library/react-hooks vs @testing-library/react across React versions), using `any` types may be necessary due to unstable type dependencies, rather than importing specific types that may not be available in all test configurations.
.github/workflows/test.yml (1)
Learnt from: davemecha
PR: davemecha/use-async-effekt#3
File: src/__tests__/test-utils.ts:6-8
Timestamp: 2025-06-29T11:06:37.033Z
Learning: In matrix testing scenarios where different versions of testing libraries are dynamically installed (like @testing-library/react-hooks vs @testing-library/react across React versions), using `any` types may be necessary due to unstable type dependencies, rather than importing specific types that may not be available in all test configurations.
package.json (1)
Learnt from: davemecha
PR: davemecha/use-async-effekt#3
File: src/__tests__/test-utils.ts:6-8
Timestamp: 2025-06-29T11:06:37.033Z
Learning: In matrix testing scenarios where different versions of testing libraries are dynamically installed (like @testing-library/react-hooks vs @testing-library/react across React versions), using `any` types may be necessary due to unstable type dependencies, rather than importing specific types that may not be available in all test configurations.
README.md (1)
Learnt from: davemecha
PR: davemecha/use-async-effekt#3
File: src/__tests__/test-utils.ts:6-8
Timestamp: 2025-06-29T11:06:37.033Z
Learning: In matrix testing scenarios where different versions of testing libraries are dynamically installed (like @testing-library/react-hooks vs @testing-library/react across React versions), using `any` types may be necessary due to unstable type dependencies, rather than importing specific types that may not be available in all test configurations.
src/useAsyncMemoSuspense.ts (1)
Learnt from: davemecha
PR: davemecha/use-async-effekt#3
File: src/__tests__/test-utils.ts:6-8
Timestamp: 2025-06-29T11:06:37.033Z
Learning: In matrix testing scenarios where different versions of testing libraries are dynamically installed (like @testing-library/react-hooks vs @testing-library/react across React versions), using `any` types may be necessary due to unstable type dependencies, rather than importing specific types that may not be available in all test configurations.
src/__tests__/useAsyncMemoSuspense.test.tsx (1)
Learnt from: davemecha
PR: davemecha/use-async-effekt#3
File: src/__tests__/test-utils.ts:6-8
Timestamp: 2025-06-29T11:06:37.033Z
Learning: In matrix testing scenarios where different versions of testing libraries are dynamically installed (like @testing-library/react-hooks vs @testing-library/react across React versions), using `any` types may be necessary due to unstable type dependencies, rather than importing specific types that may not be available in all test configurations.
🔇 Additional comments (20)
src/index.ts (1)

3-3: LGTM! Clean export addition.

The new export for useAsyncMemoSuspense follows the established pattern and properly exposes the hook for external use.

src/__tests__/useAsyncMemo.test.ts (1)

7-7: LGTM! Good testing practice.

Adding jest.clearAllMocks() to the beforeEach block ensures proper test isolation by resetting all mock state between tests, preventing potential test interference.

package.json (3)

5-5: LGTM! Good addition for tree-shaking optimization.

Adding "sideEffects": false correctly indicates that this package is safe for tree-shaking, which will help bundlers eliminate unused code.


63-63: LGTM! Safe dependency upgrade.

The ts-jest upgrade from ^29.1.0 to ^29.4.0 is a minor version bump that should provide bug fixes and improvements without breaking changes.


80-81: LGTM! Appropriate coverage exclusion.

Excluding test-utils.ts files from coverage collection is correct since these are testing infrastructure files that don't need coverage tracking.

README.md (3)

5-16: LGTM! Improved badge accessibility.

Wrapping the badges with anchor tags enhances accessibility and user experience by making the badges clickable links to relevant resources.


315-315: LGTM! Necessary ESLint configuration updates.

Adding useAsyncMemoSuspense to the ESLint configuration ensures proper dependency checking for the new hook.

Also applies to: 330-330


365-410: LGTM! Comprehensive documentation for the new hook.

The documentation for useAsyncMemoSuspense is thorough and includes:

  • Clear API reference with parameters and return types
  • Important notes about SSR behavior and client component requirements
  • Proper experimental status warning
  • Practical usage example with Suspense

The SSR behavior explanation is particularly valuable for developers using Next.js and similar frameworks.

src/useAsyncMemoSuspense.ts (5)

1-8: Well-structured type definitions

The discriminated union pattern for CacheEntry provides excellent type safety and clear state management.


9-10: Correct dependency comparison implementation

Using Object.is matches React's built-in dependency comparison behavior and correctly handles edge cases like NaN and -0.


30-78: Excellent documentation

The JSDoc is comprehensive, clearly marks the hook as experimental, and provides a practical example. The SSR behavior explanation is particularly helpful.


84-89: Potential hydration mismatch

Returning undefined on the server while potentially returning a value on the client could cause hydration mismatches. Ensure consuming components handle this appropriately, perhaps by always showing the Suspense fallback initially.

Do you want me to verify if this pattern could cause hydration issues in Next.js or other SSR frameworks?


90-117: Solid implementation of Suspense integration

The cache management and promise handling logic is well-implemented:

  • Correctly handles both sync and async factories
  • Properly maintains cache entry references
  • Follows React Suspense patterns by throwing promises
src/__tests__/useAsyncMemoSuspense.test.tsx (7)

1-84: Well-structured test setup

Excellent test infrastructure with typed helper components, realistic usage examples, and proper error boundary implementation. Good application of the learning about test-utils for matrix testing.


85-160: Thorough testing of basic functionality

Good coverage of both async suspension and sync value handling. Proper use of fake timers and React Testing Library patterns.


162-211: Comprehensive error handling tests

Both synchronous and asynchronous error scenarios are well-tested with proper error boundary integration.


213-296: Excellent dependency and scoping tests

Thorough verification of dependency tracking and cache isolation through scoping. The factory call count assertions effectively verify caching behavior.


298-365: Great testing of React 18 concurrent features

Excellent test demonstrating proper Suspense behavior with startTransition, correctly verifying that stale content is shown during transitions.


622-658: Function caching test confirms the cache key issue

This test effectively demonstrates the cache key collision problem mentioned in the implementation review. When different functions are used, they should create separate cache entries, which works here only because the deps are different.


367-706: Outstanding edge case coverage

Exceptional test coverage including:

  • Cache sharing between components
  • Complex object dependencies
  • IEEE 754 zero handling (-0 vs 0)
  • Performance under rapid changes
  • Empty and undefined dependency arrays

The test suite thoroughly exercises the implementation.

@davemecha davemecha merged commit c838e76 into main Jul 18, 2025
25 checks passed
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.

3 participants