Today I Learned

TIL, 2023-05-24

How to Fix React Hydration Error in Next - Practical Guide

Reference

  • Hydration - involves attaching event handlers and states to the server-side markup during SSR. As a page loads, React reconciles the server-generated markup with the client-side markup and attaches event handlers and states.
    • If this process fails, the application might throw an error.
  • H Errors in Next can be caused by inconsistencies between server and client-rendered markup and mismatched component states.
  • This can happen when client-side-only code, such as code that depends on the window object, is executed during server rendering.
'use client';

// Imports
// ========================================================
import React, { useState, useEffect } from 'react';

// Page
// ========================================================
export default function ClientOnly({ children }: { children: React.ReactNode }) {
    // State / Props
    const [hasMounted, setHasMounted] = useState(false);

    // Hooks
    useEffect(() => {
        setHasMounted(true);
    }, [])

    // Render
    if (!hasMounted) return null;

    return (
        <div>
            {children}
        </div>
    );
};

This project is maintained by daryllxd