Skip to content

Conversation

davemecha
Copy link
Owner

@davemecha davemecha commented Jul 18, 2025

Summary by CodeRabbit

  • New Features
    • Introduced a new experimental hook for async memoization with Suspense support, now available in the public API.
  • Documentation
    • Added comprehensive API reference and usage examples for the new hook, including server/client behavior and Suspense integration.
  • Tests
    • Added an extensive test suite covering async behavior, error handling, dependency changes, cache scoping, and concurrent rendering.
    • Improved test reliability by resetting mocks before each test.
  • Chores
    • Updated a development dependency to the latest version.

davemecha and others added 4 commits July 15, 2025 16:46
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.
Copy link
Contributor

coderabbitai bot commented Jul 18, 2025

Important

Review skipped

Auto reviews are disabled on base/target branches other than the default branch.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Walkthrough

A new React hook, useAsyncMemoSuspense, was implemented to provide async memoization with Suspense integration. The hook, its API, and usage details were documented in the README. The public API was updated to export the hook, and a comprehensive test suite was added. Minor updates were made to the ESLint config and dev dependencies.

Changes

File(s) Change Summary
README.md Documented useAsyncMemoSuspense API, usage, SSR behavior, and example.
src/useAsyncMemoSuspense.ts Added useAsyncMemoSuspense hook for async memoization with Suspense and cache scoping.
src/index.ts Exported useAsyncMemoSuspense from the module's public API.
src/tests/useAsyncMemoSuspense.test.tsx Added comprehensive tests for useAsyncMemoSuspense, covering async, sync, error, deps, and scoping.
src/tests/useAsyncMemo.test.ts Added jest.clearAllMocks() to test setup for consistent test isolation.
package.json Updated ts-jest devDependency version.

Sequence Diagram(s)

sequenceDiagram
    participant Component
    participant useAsyncMemoSuspense
    participant Cache
    participant Promise

    Component->>useAsyncMemoSuspense: Call hook with factory, deps, options
    useAsyncMemoSuspense->>Cache: Check for cached entry (by factory+deps+scope)
    alt Cache hit and resolved
        useAsyncMemoSuspense-->>Component: Return cached result
    else Cache hit and pending
        useAsyncMemoSuspense-->>Component: Throw pending promise (suspend)
    else Cache hit and error
        useAsyncMemoSuspense-->>Component: Throw error
    else Cache miss or deps changed
        useAsyncMemoSuspense->>Promise: Call factory (async or sync)
        Promise-->>useAsyncMemoSuspense: Resolves or rejects
        useAsyncMemoSuspense->>Cache: Store result or error
        useAsyncMemoSuspense-->>Component: Throw pending promise (suspend)
    end
Loading

Poem

In the garden of code, where async dreams grow,
A new Suspense hook now helps data flow.
With caches and boundaries, errors in tow,
The rabbit leaps forward—memoized, aglow!
Tests and docs in bloom,
The future’s in full plume—
Suspenseful adventures await, let’s go! 🥕✨


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.

@davemecha
Copy link
Owner Author

@coderabbitai review

Copy link
Contributor

coderabbitai bot commented Jul 18, 2025

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

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 (1)
src/useAsyncMemoSuspense.ts (1)

20-28: Consider cache key generation robustness.

The current cache key generation using factory.toString() may be fragile in production environments where code is minified or when functions are dynamically generated.

Consider these alternatives for more robust cache key generation:

function getCacheKey(
  factory: () => Promise<unknown> | unknown,
  deps: DependencyList,
  scope?: string
): string {
-  // Use function toString and JSON.stringify for deps as a simple cache key
-  // In production, you might want a more sophisticated key generation
-  return JSON.stringify([factory.toString(), deps, scope || ""]);
+  // Use a WeakMap to assign unique IDs to functions for more reliable caching
+  const factoryId = getFunctionId(factory);
+  return JSON.stringify([factoryId, deps, scope || ""]);
}

However, the current approach is acceptable for most use cases and is clearly documented as simple.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between ccbea12 and 0e4d0e1.

⛔ Files ignored due to path filters (1)
  • package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (6)
  • README.md (3 hunks)
  • package.json (1 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 (6)
📓 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.
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.
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.
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.
🪛 Biome (1.9.4)
src/__tests__/useAsyncMemoSuspense.test.tsx

[error] 64-64: Don't use '{}' as a type.

Prefer explicitly define the object shape. '{}' means "any non-nullable value".

(lint/complexity/noBannedTypes)

🪛 GitHub Actions: Test
src/__tests__/useAsyncMemoSuspense.test.tsx

[error] 341-341: TypeError: (0 , react_1.startTransition) is not a function. Test failure in 'useAsyncMemoSuspense - Core Functionality › React 18 concurrent features › should work with startTransition'.

🔇 Additional comments (13)
package.json (1)

63-63: LGTM! Dependency update supports new testing requirements.

The ts-jest update from ^29.1.0 to ^29.4.0 is a minor version bump that should include improvements and bug fixes while maintaining compatibility. This aligns well with the comprehensive test suite added for the new useAsyncMemoSuspense hook.

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

7-7: Excellent addition for test isolation.

Adding jest.clearAllMocks() ensures that mock state doesn't leak between tests, improving test reliability and preventing potential flaky test results. This is a best practice that enhances the overall test suite quality.

src/index.ts (1)

3-3: Clean addition to the public API.

The export follows the established pattern and correctly exposes the new useAsyncMemoSuspense hook to library consumers.

README.md (2)

313-313: Correct ESLint configuration update.

The addition of useAsyncMemoSuspense to the additionalHooks pattern ensures proper dependency array linting for the new hook, maintaining consistency with existing hooks.

Also applies to: 328-328


363-407: Excellent comprehensive documentation.

The documentation for useAsyncMemoSuspense is thorough and well-structured:

  • Clear API reference with parameter descriptions
  • Important SSR considerations are prominently highlighted
  • Experimental status is clearly marked
  • Practical example demonstrates proper Suspense integration
  • The scope parameter usage is well explained

This provides developers with everything they need to use the hook correctly.

src/useAsyncMemoSuspense.ts (7)

3-7: Well-designed cache entry type system.

The union type for CacheEntry clearly models the three possible states (pending, success, error) with appropriate data for each state. The undefined option handles the initial case cleanly.


9-10: Correct dependency comparison implementation.

Using Object.is() for dependency comparison is the right choice as it handles edge cases like NaN and -0 correctly, matching React's own dependency comparison logic.


84-85: Clever client component enforcement.

Using useRef(undefined) to force the component to be a client component is a creative approach that leverages React's hook rules without any side effects.


87-88: Proper SSR handling.

Returning undefined on the server side ensures proper Suspense fallback behavior during hydration, preventing hydration mismatches while allowing the client to suspend appropriately.


94-112: Solid cache management and async handling.

The cache invalidation logic correctly handles dependency changes, and the promise handling properly updates the cache entry in place using Object.assign. The use of Promise.resolve() ensures both sync and async factories are handled uniformly.


114-116: Correct Suspense integration.

The return logic properly implements the Suspense pattern:

  • Returns the result when available
  • Throws errors to trigger error boundaries
  • Throws promises to suspend rendering

This follows React Suspense conventions perfectly.


30-78: Comprehensive and accurate JSDoc documentation.

The documentation clearly explains:

  • Experimental status
  • SSR behavior and client component requirement
  • Usage patterns with practical examples
  • Integration with Suspense boundaries

This will help developers understand the hook's behavior and constraints.

src/__tests__/useAsyncMemoSuspense.test.tsx (1)

298-365: Import startTransition from React to fix the test failure

The project’s package.json shows React ^18.0.0, so startTransition is available—but it isn’t in scope in your test. Add the import at the top of the file instead of conditionally skipping the test.

Locations to update:

  • src/tests/useAsyncMemoSuspense.test.tsx (near the existing React imports)

Suggested diff:

--- a/src/__tests__/useAsyncMemoSuspense.test.tsx
+++ b/src/__tests__/useAsyncMemoSuspense.test.tsx
@@ 1,5 +1,6 @@
-import React from 'react';
+import React, { startTransition } from 'react';
 import { render, screen, act, waitFor } from '@testing-library/react';
 import rtlAct from 'react-test-renderer/src/act';
 import { Suspense, startTransition } from 'react';

(If you already import React and other hooks, just include startTransition in that import.)

After this change, the “should work with startTransition” test will run as intended under React 18.

Likely an incorrect or invalid review comment.

@codecov-commenter
Copy link

codecov-commenter commented Jul 18, 2025

⚠️ 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!

@davemecha davemecha merged commit d1c9956 into develop Jul 18, 2025
13 checks passed
@davemecha davemecha deleted the feat/add-use-async-memo-suspense branch July 18, 2025 21:01
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