Skip to content

Commit

Permalink
fix: zustand persist로 테마 데이터 저장
Browse files Browse the repository at this point in the history
  • Loading branch information
whitedev7773 committed Nov 6, 2024
1 parent c6927ab commit 83f2166
Showing 1 changed file with 35 additions and 55 deletions.
90 changes: 35 additions & 55 deletions src/hooks/theme/useTheme.js
Original file line number Diff line number Diff line change
@@ -1,66 +1,46 @@
import { useState, useEffect } from 'react';

const useTheme = () => {
// 초기 테마 설정
const getInitialTheme = () => {
const savedTheme = localStorage.getItem('theme');
if (savedTheme) {
return savedTheme;
}
const systemPrefersDark = window.matchMedia(
'(prefers-color-scheme: dark)',
).matches;
return systemPrefersDark ? 'dark' : 'light';
};

const [theme, setTheme] = useState(getInitialTheme);

// 테마를 적용하는 함수
const applyTheme = (theme) => {
const lightThemeLink = document.getElementById('light-theme');
const darkThemeLink = document.getElementById('dark-theme');
import { useEffect } from 'react';
import { create } from 'zustand';
import { persist } from 'zustand/middleware';

const getInitialTheme = () => {
const savedTheme = localStorage.getItem('theme');
return (
savedTheme ||
(window.matchMedia('(prefers-color-scheme: dark)').matches
? 'dark'
: 'light')
);
};

if (theme === 'dark') {
if (darkThemeLink) darkThemeLink.disabled = false;
if (lightThemeLink) lightThemeLink.disabled = true;
} else {
if (darkThemeLink) darkThemeLink.disabled = true;
if (lightThemeLink) lightThemeLink.disabled = false;
}
};
const useThemeStore = create(
persist(
(set) => ({
theme: getInitialTheme(),
setTheme: (theme) => set({ theme }),
}),
{ name: 'theme' },
),
);

// 초기 로드 시 테마 적용
useEffect(() => {
applyTheme(theme);
localStorage.setItem('theme', theme);
}, [theme]);
const useTheme = () => {
const { theme, setTheme } = useThemeStore();

// 시스템 테마 변경 감지
useEffect(() => {
const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)');

const systemThemeChangeListener = (e) => {
const newSystemPrefersDark = e.matches;
const savedTheme = localStorage.getItem('theme');

if (!savedTheme) {
setTheme(newSystemPrefersDark ? 'dark' : 'light');
}
const themes = {
light: { dark: true, light: false },
dark: { dark: false, light: true },
};

mediaQuery.addEventListener('change', systemThemeChangeListener);

return () => {
mediaQuery.removeEventListener('change', systemThemeChangeListener);
};
}, []);
['light', 'dark'].forEach((type) => {
const link = document.getElementById(`${type}-theme`);
if (link) link.disabled = themes[theme][type];
});
}, [theme]);

// 테마를 토글하는 함수
const toggleTheme = () => {
setTheme((prev) => (prev === 'light' ? 'dark' : 'light'));
return {
theme,
toggleTheme: () => setTheme(theme === 'light' ? 'dark' : 'light'),
};

return { theme, toggleTheme };
};

export default useTheme;

0 comments on commit 83f2166

Please sign in to comment.