necolas / react-native-web

Cross-platform React UI packages
https://necolas.github.io/react-native-web
MIT License
21.6k stars 1.79k forks source link

Image in SSR #2650

Open abaf6789 opened 6 months ago

abaf6789 commented 6 months ago

Is there an existing 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
  })