23년 07월 22일

1. 페이지 새로고침 시 경고창 노출

주니어 개발자에게 다양한 퀴즈를 제공하는 서비스를 개발하던 중 페이지를 벗어나게 되는 경우 해당 정보가 날아갈 수 있다는 경고창을 띄워주는 기능이 필요했다. 구글링을 통해 알아보니 window 객체의 beforeunload 이벤트를 통해 브라우저 새로고침을 감지하고 경고창을 띄울 수 있다고 한다.

2. 구현 코드

next.js에서 사용하였기 때문에 재사용하기 위해 커스텀훅으로 작성해보았다.

우선 아래 코드는 커스텀훅을 작성한 코드이다.

// src/hooks/useRefreshWarning.ts
import { useEffect } from 'react';

interface RefreshWarningModalProps {
    isOpen: boolean;
}

const RefreshWarningModal = ({ isOpen } : RefreshWarningModalProps) => {
    if(!isOpen) return null

    const handleBeforeUnload = (e:BeforeUnloadEvent) => {
        e.preventDefault();
        e.returnValue = "";
    }

    useEffect(() => {
        window.addEventListener('beforeunload', handleBeforeUnload);

        return () => {
            window.removeEventListener('beforeunload', handleBeforeUnload);
        };
    },[])

    return null;
};

export default RefreshWarningModal;

위 커스텀훅을 아래와 같이 사용하였다. isOpen Props를 전달하는 이유는 특정 조건에 따라 경고 모달이 노출되도록 추가하였다.

import RefreshWarningModal from '~/hooks/useRefreshWarning';
...

return (
    <div>
        <RefreshWarningModal isOpen={true}/>
        ...
    </div>
)

export default Play;

결과는 아래 이미지와 같다.

스크린샷 2023-07-22 12.03.12.png

# 레퍼런스