[ReactJS] Hooks(5)

찐새·2022년 2월 23일
0

react-hooks

목록 보기
5/7

useConfirm

이번에 배운 훅은 useStateuseEffect를 사용하지 않은 훅이다. 버튼을 눌렀을 때 등장하는 window.confirm()에 반응하여, 확인을 눌렀을 때와 취소를 눌렀을 때 작동한다.

const useConfirm = (message, onConfirm, onCancel) => {
  if (!onConfirm || typeof onConfirm !== "function") {
    return;
  }
  if (!onCancel && typeof onConfirm !== "function") {
    return;
  }
  const confirmAction = () => {
    if (window.confirm(message)) {
      onConfirm();
    } else {
      onCancel();
    }
  };
  return confirmAction;
};

3개의 인자를 받지만, 두 번째 인자(onConfirm)만 필수고 세 번째 인자(onCancel)는 옵션이다. confirmAcrion함수를 리턴하며, 확인을 눌렀을 때는 onConfirm()을, 취소를 눌렀을 때는 onCancel()을 실행한다.


usePreventLeave

페이지에서 이탈하려고 할 때 나오는 경고창 설정 훅이다. Protect 버튼을 클릭하면 이벤트가 연결되어 페이지 이탈 시 경고창을 한 번 거친다. Unprotect 버튼을 클릭하면 이벤트가 해제되어 경고창이 생성되지 않는다. 각각의 버튼을 누른 후 새로고침 버튼을 통해 확인할 수 있다.

const usePreventLeave = () => {
  const listener = (event) => {
    event.preventDefault();
    event.returnValue = "";
  };
  const enablePrevent = () => window.addEventListener("beforeunload", listener);
  const disablePrevent = () =>
    window.removeEventListener("beforeunload", listener);
  return { enablePrevent, disablePrevent };
};

const { enablePrevent, disablePrevent } = usePreventLeave();

<button onClick={enablePrevent}>Protect</button>
<button onClick={disablePrevent}>Unprotect</button>

listener 내부의 event.returnValue는 아무 값이나 줘도 상관 없다. usePreventLeave의 값을 가져올 때 주의할 점은 내부 함수와 onClick 함수의 이름이 동일해야 한다는 점이다. 중괄호{}는 변수가 아닌 프로퍼티여서 일치하지 않으면 아무런 동작도 하지 않는다.

풀어서 설명하면, usePreventLeave()에는 enablePrevent: enablePrevent()disablePrevent: disablePrevent()가 존재한다. 그 key를 정확하게 호출해야 가진 값을 사용할 수 있다. 중괄호는 내부 key를 부르는 형식이라고 보면 된다. ES6에서 event.target.valuecosnt {target : {value}} = event로 호출하는 것과 같다.

profile
프론트엔드 개발자가 되고 싶다

0개의 댓글