Skip to content

Commit

Permalink
[FE] REFACTOR: 반복되는 로직 custom hook 에 추가 #1649
Browse files Browse the repository at this point in the history
  • Loading branch information
gykoh42 committed Dec 19, 2024
1 parent ad9486c commit 9038ebd
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 15 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import {
DisplayStyleToggleType,
DisplayStyleType,
} from "@/Cabinet/types/enum/displayStyle.type.enum";
import useDisplayStyleToggle from "@/Cabinet/hooks/useDisplayStyleToggle";
import {
isDeviceDarkMode,
updateBodyDisplayStyle,
Expand All @@ -32,6 +33,7 @@ export const getInitialDisplayStyle = (
const DisplayStyleCardContainer = () => {
const darkModeQuery = isDeviceDarkMode();
const toggleType = useRecoilValue(displayStyleState);
const { addDarkModeListener } = useDisplayStyleToggle();

useEffect(() => {
const applyDisplayStyle = () => {
Expand All @@ -40,13 +42,7 @@ const DisplayStyleCardContainer = () => {
};

applyDisplayStyle();

if (toggleType === DisplayStyleToggleType.DEVICE) {
darkModeQuery.addEventListener("change", applyDisplayStyle);
return () => {
darkModeQuery.removeEventListener("change", applyDisplayStyle);
};
}
addDarkModeListener(darkModeQuery, applyDisplayStyle);
}, [toggleType]);

return <DisplayStyleCard />;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ const DarkModeToggleSwitch = ({ id }: { id: string }) => {
);

const isDarkMode = displayStyleType === DisplayStyleType.DARK;
const { updateToggleType } = useDisplayStyleToggle();
const { updateToggleType, addDarkModeListener } = useDisplayStyleToggle();

useEffect(() => {
setToggleType(getDisplayStyleFromLocalStorage());
Expand All @@ -45,12 +45,7 @@ const DarkModeToggleSwitch = ({ id }: { id: string }) => {
};

updateDisplayStyleType();
if (toggleType === DisplayStyleToggleType.DEVICE) {
darkModeQuery.addEventListener("change", updateDisplayStyleType);
return () => {
darkModeQuery.removeEventListener("change", updateDisplayStyleType);
};
}
addDarkModeListener(darkModeQuery, updateDisplayStyleType);
}, [toggleType]);

useEffect(() => {
Expand Down
13 changes: 12 additions & 1 deletion frontend/src/Cabinet/hooks/useDisplayStyleToggle.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,18 @@ export const useDisplayStyleToggle = () => {
updateLocalStorageDisplayStyleToggle(newToggleType);
};

return { updateToggleType };
const addDarkModeListener = (
darkModeQuery: MediaQueryList,
callback: () => void
) => {
if (toggleType === DisplayStyleToggleType.DEVICE) {
darkModeQuery.addEventListener("change", callback);
return () => {
darkModeQuery.removeEventListener("change", callback);
};
}
};
return { updateToggleType, addDarkModeListener };
};

export default useDisplayStyleToggle;

0 comments on commit 9038ebd

Please sign in to comment.