🔥 문제
드디어 올 게 오고야 말았다. 누수 이슈.
이를 어떻게 해결해야 할까?

⭐ 해결 방법
먼저, 해당 오류의 원천인
MainPage
에서의 로그를 클릭해본다. 친절하게도, 여기서의 오류라고 브라우저에서 알려준다.

오호, 그렇다면 우리는 매우 간단해졌다.
modalVisible
에서의 state
를 useEffect
를 통해 관리하면 어떨까?결과적으로
useEffect
는 unmounted
할 때 cleanup function
으로 state 값을 처리해줄 것이고... 따라서 메모리 누수를 방지해줄 수 있는 것이다.따라서
Header
부분에서 useEffect
로 state
를 정리해준다.import React, { ReactNode, useEffect, useState } from 'react'; import styled from '@emotion/styled'; import { Text, Icon } from '@components/atoms'; import { css } from '@emotion/react'; import { MdOutlineMenu, MdOutlineArrowBackIosNew } from 'react-icons/md'; import logo from '../../../public/logo.svg'; import { NavModal, NavModalInner } from './NavModal'; export interface HeaderProps { children?: ReactNode; size?: string | number; width?: string | number; height?: string | number; display?: 'none' | 'flex'; isLogo?: boolean; isVisibleMenu?: boolean; isVisiblePrev?: boolean; src?: string; justifyContent?: 'none' | 'space-between'; onMenuClick?: () => void; } const HeaderContainer = styled.div` padding: 0; margin: 0; `; const HeaderSection = styled.div` ${({ width, height, justifyContent }: Partial<HeaderProps>) => css` display: flex; align-items: center; justify-content: ${justifyContent || 'none'}; width: ${typeof width === 'string' ? width : `${width}px`}; height: ${typeof height === 'string' ? height : `${height}px`}; `} `; const Image: React.FC<HeaderProps> = styled.img` ${({ size }: Partial<HeaderProps>) => css` height: ${typeof size === 'string' ? size : `${size}px`}; `} `; const Header: React.FC<HeaderProps> = ({ children, width = 'auto', height = 48, size = 24, justifyContent = 'none', isVisiblePrev = true, isVisibleMenu = true, ...props }) => { const [navModalVisible, setNavModalVisible] = useState<boolean>(false); useEffect(() => { return () => setNavModalVisible(() => false); }, []); const handleMenuClick = () => { setNavModalVisible(() => true); }; const handleNavModalClose = () => { setNavModalVisible(() => false); }; return ( <HeaderContainer {...props}> <HeaderSection width={width} height={height} justifyContent="space-between" > <Image src={logo.src} width={logo.width} height={logo.height} /> {isVisibleMenu && ( <Icon size={size}> <MdOutlineMenu onClick={handleMenuClick} /> </Icon> )} </HeaderSection> {isVisiblePrev && ( <HeaderSection width={width} height={height} justifyContent={justifyContent} > <Icon size={size}> <MdOutlineArrowBackIosNew /> </Icon> <Text size="small">뒤로</Text> </HeaderSection> )} <NavModal visible={navModalVisible} onClose={handleNavModalClose}> <NavModalInner userType="owner" /> </NavModal> </HeaderContainer> ); }; export default Header;
결과
오류가 발생하지 않았다!
