fix(use-theme): add SSR safety guards for window access
setTheme, toggleTheme, and storage event listener now check typeof window before accessing localStorage/addEventListener. Prevents crashes in Next.js server components.
This commit is contained in:
parent
6f4957d821
commit
e194365711
@ -49,6 +49,8 @@ export function useTheme(options?: UseThemeOptions): UseThemeReturn {
|
||||
|
||||
// Sync across tabs via storage event
|
||||
useEffect(() => {
|
||||
if (typeof window === 'undefined') return;
|
||||
|
||||
function handleStorage(event: StorageEvent) {
|
||||
if (event.key !== storageKey) {
|
||||
return;
|
||||
@ -65,7 +67,9 @@ export function useTheme(options?: UseThemeOptions): UseThemeReturn {
|
||||
const setTheme = useCallback(
|
||||
(t: Theme) => {
|
||||
setThemeState(t);
|
||||
window.localStorage.setItem(storageKey, t);
|
||||
if (typeof window !== 'undefined') {
|
||||
window.localStorage.setItem(storageKey, t);
|
||||
}
|
||||
},
|
||||
[storageKey]
|
||||
);
|
||||
@ -73,7 +77,9 @@ export function useTheme(options?: UseThemeOptions): UseThemeReturn {
|
||||
const toggleTheme = useCallback(() => {
|
||||
setThemeState(prev => {
|
||||
const next: Theme = prev === 'dark' ? 'light' : 'dark';
|
||||
window.localStorage.setItem(storageKey, next);
|
||||
if (typeof window !== 'undefined') {
|
||||
window.localStorage.setItem(storageKey, next);
|
||||
}
|
||||
applyTheme(next, attribute);
|
||||
return next;
|
||||
});
|
||||
|
||||
Loading…
Reference in New Issue
Block a user