Hydration issues in Remix
2023-08-11
Imagine building a puzzle. You perfectly place every piece, but when you return, you find someone added extra pieces. Now, your puzzle doesn't fit together. This is what happens with Remix and React 18. When React 18 sees this mismatch, it throws away everything and starts anew, causing more problems.
How To Solve It:
Before Remix, other tools put their app inside a box (or
<div>
) on the webpage. This made sure nothing outside messed with it.
How to Fix in Remix:
Divide Your App: Think of your app in two parts. One is the top (
<Head>
) and the other is the main part (inside a box<div id="root"/>
).Change
root.tsx
: Initially, everything from the top to the bottom was together. Now, we split them. We keep the top part in its place but don't use the usual<head>
tag.Why Use
<Head>
Twice?: We use<Head>
in the main part so that when a user moves around the site, the website's top links and info update properly.Proper Order Matters: While showing the top (
<Head>
), make sure it's in its right spot, away from the main box. For this, we use a special React tool called a "portal." But to avoid the first problem, we make sure this is done only after everything is ready.On the Server in
entry.server.tsx
: Here, we want the top part to be fixed, like a painted picture. The rest should be fluid, like streaming water. So, we use comments (<!--start head--><!--end head-->
) to mark the fixed part.On Your Computer in
entry.client.tsx
: After the website is ready, we want to make sure everything fits perfectly. We have to remove the old top (<Head>
) before showing the new one to avoid having two tops.
And that's it! With these steps, the Remix app with React should work smoothly without any refresh issues.