drago.cc

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 I think 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".

  1. 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.
  2. 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.
  3. 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.

Created on Sunday, July 25, 2021, 5:22 PM UTC

The golden rule of design systems

Components shouldn't contain surrounding white space.

Components should be able to be used in any context. You shouldn't need to remove or adjust the surrounding white space every time you use a component. Doing so diminishes some of utility of having a design system. The goal of which should be to allow you to write as little CSS as possible.

Unfortunately, text elements in browsers break this rule since they place text in the middle of the box formed from the text's line height, always resulting in white space above and below each line of text. Tools like Capsize can help with this by cropping the white space above and below each text element.

Once you've removed white space from your components, control the "gap" between them by using a parent "layout" component.

I highly recommend watching this talk from ReactConf AU by Mark Dalgleish to learn more about this concept.

Created on Sunday, July 11, 2021, 6:04 PM UTC