Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(use-image): cached image flickering issue #4442

Open
wants to merge 6 commits into
base: canary
Choose a base branch
from

Conversation

wingkwong
Copy link
Member

@wingkwong wingkwong commented Dec 25, 2024

📝 Description

⛳️ Current behavior (updates)

🚀 New behavior

pr4442-demo.webm

💣 Is this a breaking change (Yes/No):

📝 Additional Information

Summary by CodeRabbit

  • New Features

    • Introduced useIsHydrated hook for determining component hydration status.
    • Enhanced useImage hook with hydration checks to improve image loading behavior.
  • Bug Fixes

    • Resolved flickering issue with cached images in the use-image package.
  • Tests

    • Added a new test case for handling cached images in the useImage hook.
  • Chores

    • Updated dependencies in the use-image package to include @nextui-org/react-utils.

Copy link

linear bot commented Dec 25, 2024

Copy link

vercel bot commented Dec 25, 2024

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
nextui-docs-v2 ✅ Ready (Inspect) Visit Preview 💬 Add feedback Dec 25, 2024 4:20pm
nextui-storybook-v2 ✅ Ready (Inspect) Visit Preview 💬 Add feedback Dec 25, 2024 4:20pm

Copy link

changeset-bot bot commented Dec 25, 2024

🦋 Changeset detected

Latest commit: 1239c07

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 50 packages
Name Type
@nextui-org/react-utils Patch
@nextui-org/use-image Patch
@nextui-org/accordion Patch
@nextui-org/alert Patch
@nextui-org/autocomplete Patch
@nextui-org/avatar Patch
@nextui-org/badge Patch
@nextui-org/breadcrumbs Patch
@nextui-org/button Patch
@nextui-org/calendar Patch
@nextui-org/card Patch
@nextui-org/checkbox Patch
@nextui-org/chip Patch
@nextui-org/code Patch
@nextui-org/date-input Patch
@nextui-org/date-picker Patch
@nextui-org/drawer Patch
@nextui-org/dropdown Patch
@nextui-org/form Patch
@nextui-org/image Patch
@nextui-org/input-otp Patch
@nextui-org/input Patch
@nextui-org/kbd Patch
@nextui-org/link Patch
@nextui-org/listbox Patch
@nextui-org/menu Patch
@nextui-org/modal Patch
@nextui-org/navbar Patch
@nextui-org/pagination Patch
@nextui-org/popover Patch
@nextui-org/progress Patch
@nextui-org/radio Patch
@nextui-org/ripple Patch
@nextui-org/scroll-shadow Patch
@nextui-org/select Patch
@nextui-org/skeleton Patch
@nextui-org/slider Patch
@nextui-org/snippet Patch
@nextui-org/spacer Patch
@nextui-org/spinner Patch
@nextui-org/switch Patch
@nextui-org/table Patch
@nextui-org/tabs Patch
@nextui-org/tooltip Patch
@nextui-org/user Patch
@nextui-org/system Patch
@nextui-org/use-real-shape Patch
@nextui-org/react Patch
@nextui-org/aria-utils Patch
@nextui-org/framer-utils Patch

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

Copy link
Contributor

coderabbitai bot commented Dec 25, 2024

Walkthrough

This pull request introduces a new utility hook useIsHydrated in the @nextui-org/react-utils package and updates the useImage hook to address cached image flickering issues. The changes focus on improving image rendering behavior, particularly for server-side rendered applications, by adding hydration state checks and enhancing the image loading mechanism.

Changes

File Change Summary
packages/utilities/react-utils/src/use-is-hydrated.ts Added new useIsHydrated() hook to determine component hydration state
packages/utilities/react-utils/src/index.ts Exported useIsHydrated from new module
packages/hooks/use-image/src/index.ts Restructured useImage hook to incorporate hydration checks
packages/hooks/use-image/package.json Added @nextui-org/react-utils as a dependency
packages/hooks/use-image/__tests__/use-image.test.tsx Added test case for handling cached images

Assessment against linked issues

Objective Addressed Explanation
Fix cached avatar flickering [#4271, #3437]
Render cached images instantly

Possibly related PRs

Suggested labels

📋 Scope : Docs

Suggested reviewers

  • jrgarciadev

Tip

CodeRabbit's docstrings feature is now available as part of our Early Access Program! Simply use the command @coderabbitai generate docstrings to have CodeRabbit automatically generate docstrings for your pull request. We would love to hear your feedback on Discord.


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ 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.
    • Generate unit testing code for this file.
    • 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 generate unit testing code for this file.
    • @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 generate unit testing code.
    • @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.

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. (Beta)
  • @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.

@wingkwong wingkwong changed the title Fix/eng 1123 fix(use-image): cached image flickering issue Dec 25, 2024
@wingkwong wingkwong added this to the v2.6.11 milestone Dec 25, 2024
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 (2)
packages/hooks/use-image/__tests__/use-image.test.tsx (1)

37-43: New test coverage for cached images
This test effectively confirms that the hook resolves the appropriate status when the image is already loaded (cached). Consider adding an SSR-focused test if feasible, to ensure hydration behavior is validated in the test suite.

.changeset/small-kids-walk.md (1)

1-5: Concise changeset entry
The summary succinctly documents the addition of useIsHydrated. If you wish to also mention that it addresses cached image flickering, consider including a brief note. Otherwise, this is acceptable as-is.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 388b2ed and 1239c07.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (7)
  • .changeset/small-kids-walk.md (1 hunks)
  • .changeset/tame-glasses-press.md (1 hunks)
  • packages/hooks/use-image/__tests__/use-image.test.tsx (1 hunks)
  • packages/hooks/use-image/package.json (1 hunks)
  • packages/hooks/use-image/src/index.ts (3 hunks)
  • packages/utilities/react-utils/src/index.ts (1 hunks)
  • packages/utilities/react-utils/src/use-is-hydrated.ts (1 hunks)
🔇 Additional comments (8)
packages/hooks/use-image/src/index.ts (4)

7-8: Properly imported dependencies
These imports correctly introduce the necessary React hooks as well as the useIsHydrated utility.


106-130: Image setup and initial status calculation
The helper function setImageAndGetInitialStatus responsibly handles image attributes (such as crossOrigin, srcSet, etc.). This is well-designed and clear. Keep in mind that if more image properties are introduced, they should also be set here for consistency.


132-136: Informative fallback-check helper
shouldShowFallbackImage and its usage of fallbackStrategy are straightforward and enhance code readability.


68-76: Conditionally creating the Image object based on hydration
This logic correctly defers image instantiation until hydration occurs, mitigating server-side rendering conflicts. However, please verify if any race condition could arise when isHydrated transitions from false to true.

✅ Verification successful

Let me gather more information about the implementation of useIsHydrated and the image loading logic.


Let me check the effect hooks and status updates in the image component.


No race conditions found in hydration-based image instantiation

The implementation is safe from race conditions for the following reasons:

  1. useIsHydrated uses useSyncExternalStore which guarantees consistent hydration state transitions
  2. The initial image state is properly set during component initialization
  3. The useEffect hook properly handles cleanup through the flush function
  4. Image loading events are correctly managed regardless of when hydration occurs

The code correctly handles both the server-side rendering phase (where isHydrated is false) and the client-side hydration phase, with proper cleanup and state management.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Searching for all usage of `isHydrated` to ensure consistent updates.
rg -A 3 "isHydrated"

Length of output: 1081


Script:

#!/bin/bash
# Check the implementation of useIsHydrated
cat packages/utilities/react-utils/src/use-is-hydrated.ts

# Check the implementation of setImageAndGetInitialStatus and related effects
ast-grep --pattern 'function setImageAndGetInitialStatus($_) { $$$ }'

Length of output: 743


Script:

#!/bin/bash
# Check the implementation of useEffect hooks and status management
ast-grep --pattern 'useEffect(() => { $$$ })'

# Check the full implementation of the image hook
cat packages/hooks/use-image/src/index.ts

Length of output: 3774

packages/utilities/react-utils/src/use-is-hydrated.ts (1)

1-30: Efficient use of useSyncExternalStore
This hook leverages useSyncExternalStore properly and returns a stable hydration state. The no-op subscription strategy is appropriate, given that you do not expect external triggers.

packages/utilities/react-utils/src/index.ts (1)

36-36: Export for useIsHydrated
Exposing useIsHydrated aligns well with the rest of the utilities and maintains consistency in the package’s index.

.changeset/tame-glasses-press.md (1)

1-5: LGTM! Changeset correctly documents the patch.

The changeset properly indicates a patch version bump for the use-image package and references the relevant issue #4271.

packages/hooks/use-image/package.json (1)

37-38: LGTM! Dependencies are properly configured.

The addition of @nextui-org/react-utils as a workspace dependency is correct and follows the existing pattern. This dependency is required for the new hydration check functionality.

Let's verify the usage of the new dependency:

✅ Verification successful

The dependency is correctly used and properly imported

The @nextui-org/react-utils dependency is being used correctly in the package. The useIsHydrated hook is imported from this package and is used within the useImage hook to handle hydration-aware image loading. The implementation shows proper integration with the hydration check functionality.

Key usage points:

  • Imported at the top: import {useIsHydrated} from "@nextui-org/react-utils"
  • Used to initialize the image ref: const isHydrated = useIsHydrated()
  • Affects the initial state and image creation logic based on hydration status
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the import and usage of useIsHydrated from react-utils
# Expected: Find imports of useIsHydrated in the use-image package

rg -t ts -t tsx "useIsHydrated|@nextui-org/react-utils" packages/hooks/use-image/

Length of output: 111


Script:

#!/bin/bash
# Let's try a different approach to find the imports and usage
# First, let's check all TypeScript files in the use-image package
fd '\.(ts|tsx)$' packages/hooks/use-image/ --exec rg -l "@nextui-org/react-utils|useIsHydrated" {}

# Let's also check the package contents
cat packages/hooks/use-image/src/use-image.ts

Length of output: 262


Script:

#!/bin/bash
# Let's check the content of index.ts since it matched our search
cat packages/hooks/use-image/src/index.ts

# Let's also check if there are any other source files in the package
fd '\.(ts|tsx)$' packages/hooks/use-image/src/

Length of output: 3813

packages/hooks/use-image/src/index.ts Show resolved Hide resolved
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.

[BUG] - 2.6.4 Cached Avatars Still Flickering [Avatar] Fix flashing when image is already cached
1 participant