Hydration failed in next.js

1. Phenomenon:

Preliminarily use css媒体查询and , react-responsiverespectively useMediaQuery, to compare the switching between the mobile terminal and the PC terminal. Use useMediaQuerycan quickly get the current media query through js, so as to determine whether the current screen is a widescreen or a mobile screen. Hydration failed because the initial UI does not match what was rendered on the serveHowever, when the page is refreshed on the PC side, an error message will be displayed .error.gif

2. Reason:

Mainly the HTML rendered on the server side doesn't match the HTML rendered on the client side

3. Solve:

You can use useMediaQuery++ , Dynamic Importand React-lazydynamic import can delay loading components and modules, so that only necessary components and modules are rendered during server-side rendering (SSR), thereby reducing the possibility of inconsistency between the server and client ui. The overall effect is as shown (refresh the page on the mobile terminal and the PC terminal respectively, and the loading effect will appear, and then switch from the mobile terminal to the PC terminal or switch from the PC terminal to the mobile terminal, and there will be no loading field):complete.gif

import dynamic from 'next/dynamic'

const MyComponentWithMediaQuery = dynamic(() => import('./MyComponentWithMediaQuery'), 
{
  ssr: false ,loading: () => <p>Loading...</p>
})

function MyPage() {
  return <MyComponentWithMediaQuery />
}
import { useDesktopQuery } from "@/util/useHooks";

const MyComponentWithMediaQuery = () => {
  const flag = useDesktopQuery();
  return <>{flag && "pc页面"}</>;
};

export default MyComponentWithMediaQuery;


4. Results:

  • 1. You can use css media query @mediato process it into a responsive style, which can quickly switch between mobile and pc. Note: If there is too much difference in the page structure between the PC end and the mobile end, the page file size will become larger
  • 2. The specific page first screen solution can be prioritized when the structure changes little css媒体查询. Dynamic import can be used for other page situations, which can ensure the experience effect of the first screen

Guess you like

Origin juejin.im/post/7255955134131535932