How to fix hydration errors in Nextjs theme change

Hydration error is a very common error in Nextjs.

In order for hydration to function correctly, the initial client-side rendered version of the UI must be identical to the server-side one. 

 However, in this case, the resolvedTheme variable is undefined on the server and a string on the client, causing the React trees rendered on the server and client to be different. As a result, hydration fails.

To fix this we need to ensure we don’t consume the resolvedTheme variable in the first component render:

In this case, we are using the value of the mounted state to ensure that our component has been rendered client side at least once before attempting to access the resolvedTheme variable. At this moment the React trees on both client and server look like this:

Leave a comment

Your email address will not be published. Required fields are marked *