Hydration failed because initial UI does not match server-rendered HTML when reading localStorage in Next.js 14
I am using the Next.js 14 App Router to load a user theme preference from localStorage in a component. I get an error on page load: Error: Hydration failed because the initial UI does not match what was rendered on the server. Component code: 'use client'; import { useState } from 'react'; export default function ThemeComponent() { // Attempting to read directly from localStorage during initialization const [theme, setTheme] = useState(localStorage.getItem('theme') || 'light'); return ( <div className={theme === 'dark' ? 'bg-black text-white' : 'bg-white text-black'}> Current theme: {theme} </
0 upvotes
View original discussion ↗
Comments
Sign in or sign up to comment and upvote.
No comments yet.