til / Solving my hydration issues in react 18
After upgrading this site to React 18, I started getting hydration errors. These are errors that occur when the output from the server doesn’t match the output in the client. The site was working, but with ugly CSS flashing. These issues only appeared in production, which meant it was hard tracking down what was wrong.
I tried fixing it and gave up on two different occasions, each time thinking that I was doing something wrong with the updated React setup and Remix (how I migrated to Remix). On my third attempt, I decided to check every page to narrow down what could be causing the issue.
I found one page where the errors didn’t occur. Using a combination of “View Page source” (server rendered HTML) and “Inspect element” (client rendered HTML) I was able to deduce that the errors came from a mismatch in date rendering.
I use Intl’s DateTimeFormat
, but it seems like Node and browsers handle timezones differently. I’m not concerned with the timezone, I just want to display dates for whatever the time was for me the post was created.
To solve it, I only needed to pass a timeZone
key with CET (my timezone) to DateTimeFormat
and all my errors disappeared.
// Before
const dateFormatter = (options) => new Intl.DateTimeFormat("sv-SE", options);
// After
const dateFormatter = (options) =>
new Intl.DateTimeFormat("sv-SE", { timeZone: "CET", ...options });