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

Image in SSR #2650

Open
1 task done
abaf6789 opened this issue Mar 12, 2024 · 0 comments
Open
1 task done

Image in SSR #2650

abaf6789 opened this issue Mar 12, 2024 · 0 comments
Labels
enhancement Requires extension or creation of new React Native API

Comments

@abaf6789
Copy link

Is there an existing request?

  • I have searched for this request

Describe the feature request

https://github.com/necolas/react-native-web/blob/master/packages/react-native-web/src/exports/Image/index.js

const [state, updateState] = React.useState(() => {
    const uri = resolveAssetUri(source);
    if (uri != null) {
      const isLoaded = ImageLoader.has(uri);
      if (isLoaded) {
        return LOADED;
      }
    }
    return IDLE;
  });

In a Server-Side Rendering (SSR) scenario, we aim for the page to render tags directly on the initial load to avoid discrepancies in content that would cause re-renders during the client-side hydration process, thereby enhancing user experience. However, the use of the React useState hook for initializing state in the code snippet above may lead to issues.

The root of the problem lies in the logic of the useState initialization function, which attempts to determine if the image has been loaded. If the image is not loaded, it sets the state to IDLE. On the server side, since there is no concept of image loading, the state is always set to IDLE, resulting in tags not being included in the server-rendered HTML. When the client takes over rendering (i.e., during the hydration process), React detects a mismatch between the server-rendered content and the expected state on the client, triggering a re-render. This not only affects performance but may also cause the user to see a flicker in the page content.

Below is the modified code:

const [state, updateState] = useState(() => {
    const uri = resolveAssetUri(source)
    if (uri != null) {
      const isLoaded = ImageLoader.has(uri)
      if (isLoaded) {
        return LOADED
      } else {
        return LOADING
      }
    }
    return IDLE
  })
@abaf6789 abaf6789 added the enhancement Requires extension or creation of new React Native API label Mar 12, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement Requires extension or creation of new React Native API
Projects
None yet
Development

No branches or pull requests

1 participant