Why it's important for server and client to match in SSR
I learned some very valuable lessons about SSR and hydration this week. Some people might already have learned these lessons, but I figured I'd share anyway.
Don't ignore that Next warning message:
Warning: X did not match. Server: "<What next rendered on the server>" Client: "<What next rendered on the client>"
It'll probably bite you if you do.
The crux of it is that, in Next, you should try to stay away from manipulating the HTML in such a way that the server's HTML is different than the client's HTML. Especially when it comes to images, but it applies to all elements. This will always result in a shift in the page, even if your first client-side render has the correct HTML. As I understand it, it's all about "hydration".
- Next runs your React code and renders the HTML on the server. It then sends that HTML down to the client and shows it to the user. Your client-side React code has not run yet at this point but the user still sees your UI.
- Next "hydrates" the page with your React code, and then re-renders the page, adjusting any HTML that might've changed now that it is running on the client. This is the first render that happens on the client (i.e., you can expect that any code inside a Component function is run at this point). This is also where you'll see the above warning if any of that HTML that the server rendered doesn't match.
- After that first render, all useEffects kick in, and any code inside of them is executed, potentially causing additional renders.
The bold part of Step 1 above is the reason why it's so important not to ignore that warning.
Published: July 25, 2021 at 5:22 PM
Edited: September 9, 2023 at 1:31 PM