File size: 1,277 Bytes
5081fcb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
"use client";

import * as React from "react";
import { ThemeProvider as NextThemesProvider } from "next-themes";

/**
 * Custom ThemeProvider component that wraps next-themes provider
 * with hydration mismatch prevention.
 *
 * This component ensures theme switching functionality works correctly
 * by only rendering after initial client-side mount to prevent
 * hydration mismatches between server and client rendering.
 *
 * @param children - Child components to be wrapped by the theme provider
 * @param props - Additional props passed to NextThemesProvider
 */
export function ThemeProvider({
  children,
  ...props
}: React.ComponentProps<typeof NextThemesProvider>) {
  // Track whether component has mounted on client-side
  const [mounted, setMounted] = React.useState(false);

  // Set mounted state to true after initial client-side render
  // This ensures we only render content after hydration is complete
  React.useEffect(() => {
    setMounted(true);
  }, []);

  // Return null on server-side and initial client-side render
  // to prevent hydration mismatch with theme preferences
  if (!mounted) {
    return null;
  }

  // Once mounted, render the theme provider with children
  return <NextThemesProvider {...props}>{children}</NextThemesProvider>;
}