Custom Hook을 활용한 알림 기능 구현

지금은 웹 애플리케이션에서 사용자에게 알림을 보여주는 기능이 필수적입니다. 이번 글에서는 React에서 Custom Hook을 활용하여 간단한 알림 기능을 구현해 보겠습니다.

Custom Hook이란?

Custom Hook은 React에서 함수 컴포넌트에서 상태 관리나 로직을 추상화하기 위해 사용되는 기능입니다. 이를 통해 코드의 재사용성을 높일 수 있고, 가독성을 개선할 수 있습니다.

알림 컴포넌트 생성하기

먼저, 알림을 나타낼 컴포넌트를 생성합니다. 이 컴포넌트는 단순히 알림 메시지를 받아서 화면에 보여주는 역할을 합니다.

import React from 'react';

const Notification = ({ message }) => {
  return (
    <div className="notification">
      {message}
    </div>
  );
}

export default Notification;

Custom Hook 생성하기

이제 Custom Hook을 생성하여 알림 기능을 구현해 보겠습니다. 이 Hook은 알림 메시지를 관리하고, 알림을 보여주거나 숨길 수 있는 기능을 제공합니다.

import { useState } from 'react';

const useNotification = () => {
  const [notification, setNotification] = useState(null);

  const showNotification = (message) => {
    setNotification(message);
    setTimeout(() => {
      hideNotification();
    }, 3000);
  };

  const hideNotification = () => {
    setNotification(null);
  };

  return [notification, showNotification];
}

export default useNotification;

알림 사용하기

이제 알림을 사용하는 컴포넌트에서 Custom Hook을 호출하여 알림을 관리해보겠습니다.

import React from 'react';
import useNotification from './useNotification';
import Notification from './Notification';

const App = () => {
  const [notification, showNotification] = useNotification();

  const handleButtonClick = () => {
    showNotification("알림 메시지입니다.");
  };

  return (
    <div>
      <button onClick={handleButtonClick}>알림 보이기</button>
      {notification && <Notification message={notification} />}
    </div>
  );
}

export default App;

위와 같이 useNotification Hook을 호출하고, showNotification 함수를 사용하여 알림 메시지를 보여줄 수 있습니다. Notification 컴포넌트는 notification 상태가 존재하는 경우에만 렌더링됩니다.

결론

Custom Hook을 활용하여 React 애플리케이션에서 알림 기능을 구현하는 방법을 알아보았습니다. 이를 통해 코드의 재사용성과 가독성을 높일 수 있으며, 더욱 유연하고 확장 가능한 애플리케이션을 개발할 수 있습니다. 이러한 Custom Hook을 다양하게 활용하여 애플리케이션의 기능을 개선해보세요.

#React #CustomHook