Custom Hook을 이용한 브라우저 히스토리 관리

브라우저 히스토리 관리는 웹 애플리케이션에서 중요한 부분입니다. 사용자가 페이지를 이동하거나 뒤로 가기 버튼을 클릭할 때, 애플리케이션의 상태를 적절하게 업데이트하는 것이 필요합니다. 이를 위해 React에서는 useHistory Hook을 제공하고 있습니다.

하지만 useHistory Hook은 기본적으로 브라우저의 히스토리 API와 직접 연결되어 있어, 사용하기에는 조금 제약이 따릅니다. 그래서 우리는 Custom Hook을 만들어 브라우저 히스토리를 더욱 유연하게 관리할 수 있습니다.

Custom Hook 만들기

먼저, useCustomHistory라는 Custom Hook을 만들어 보겠습니다. 이 Hook은 push, goBack 그리고 goForward라는 세 가지 함수를 반환할 것입니다.

import { useState } from 'react';

const useCustomHistory = () => {
  const [history, setHistory] = useState([]);
  const [currentIndex, setCurrentIndex] = useState(0);

  const push = (url) => {
    setHistory([...history.slice(0, currentIndex + 1), url]);
    setCurrentIndex(currentIndex + 1);
  };

  const goBack = () => {
    if (currentIndex > 0) {
      setCurrentIndex(currentIndex - 1);
    }
  };

  const goForward = () => {
    if (currentIndex < history.length - 1) {
      setCurrentIndex(currentIndex + 1);
    }
  };

  return { push, goBack, goForward };
};

export default useCustomHistory;

위의 코드에서는 useState Hook을 사용하여 historycurrentIndex 상태를 관리합니다. push 함수는 새로운 URL을 history에 추가하고 currentIndex를 증가시킵니다. goBack 함수는 현재 인덱스를 감소시키고, goForward 함수는 현재 인덱스를 증가시킵니다.

사용 방법

사용자 정의 히스토리를 사용하기 위해 컴포넌트에서 useCustomHistory Hook을 호출하고, 반환된 함수들을 사용하면 됩니다.

import React from 'react';
import useCustomHistory from './useCustomHistory';

const MyComponent = () => {
  const { push, goBack, goForward } = useCustomHistory();

  const handleButtonClick = () => {
    push('/new-page');
  };

  return (
    <div>
      <button onClick={handleButtonClick}>Go to new page</button>
      <button onClick={goBack}>Go back</button>
      <button onClick={goForward}>Go forward</button>
    </div>
  );
};

export default MyComponent;

위의 예시에서는 버튼을 클릭할 때마다 push, goBack, goForward 함수가 호출됩니다. 이를 통해 사용자 정의 히스토리를 업데이트하고, 브라우저 히스토리를 관리할 수 있습니다.

마무리

Custom Hook을 이용하여 브라우저 히스토리를 관리하는 방법을 알아보았습니다. 이를 통해 더욱 유연하게 웹 애플리케이션의 상태를 관리할 수 있고, 사용자에게 편리한 경험을 제공할 수 있습니다. 더 자세한 내용은 React 공식 문서을 참고해보세요.

#React #CustomHook