본문 바로가기

React

React 앱에서 Toast/Notification 시스템 구축하기

React 애플리케이션에서 사용자에게 피드백을 제공하는 가장 효과적인 방법 중 하나는 Toast 또는 Notification을 사용하는 것입니다. 이번 글에서는 간단하고 확장 가능한 Toast 시스템을 직접 구현하는 방법을 다룹니다.

1. Toast 시스템 설계 개요

Toast는 화면 한켠에 잠시 나타났다 사라지는 메시지입니다. 키 포인트는 다음과 같습니다.

  • 글로벌 어디서든 호출 가능하도록 Context API를 활용합니다.
  • 컴포넌트 해체 시 알림도 자동 제거합니다.
  • 다양한 타입(성공, 에러, 정보 등)을 지원합니다.

2. Toast Context 만들기

import React, { createContext, useContext, useState, useCallback } from 'react';

const ToastContext = createContext();

export const useToast = () => useContext(ToastContext);

export const ToastProvider = ({ children }) => {
  const [toasts, setToasts] = useState([]);

  const addToast = useCallback((content, type = 'info', duration = 3000) => {
    const id = Date.now();
    setToasts(toasts => [...toasts, { id, content, type }]);
    setTimeout(() => {
      setToasts(toasts => toasts.filter(toast => toast.id !== id));
    }, duration);
  }, []);

  return (
    <ToastContext.Provider value={{ addToast }}>
      {children}
      <div className="toast-container">
        {toasts.map(({ id, content, type }) => (
          <div key={id} className={`toast toast-${type}`}>{content}</div>
        ))}
      </div>
    </ToastContext.Provider>
  );
};

3. 스타일링 및 활용법

기본 CSS 예시:

.toast-container {
  position: fixed;
  top: 1rem;
  right: 1rem;
  z-index: 9999;
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
}
.toast {
  padding: 1rem 1.5rem;
  border-radius: 4px;
  color: #fff;
  box-shadow: 0 2px 8px rgba(0,0,0,0.15);
  animation: fadein 0.3s, fadeout 0.5s 2.5s forwards;
}
.toast-info { background: #3498db; }
.toast-success { background: #2ecc71; }
.toast-error { background: #e74c3c; }

@keyframes fadein {
  from { opacity: 0; transform: translateY(-10px); }
  to { opacity: 1; transform: translateY(0); }
}
@keyframes fadeout {
  to { opacity: 0; transform: translateY(-10px); }
}

컴포넌트 사용 예시:

import React from 'react';
import { useToast } from './ToastContext';

const DemoButton = () => {
  const { addToast } = useToast();

  const handleClick = () => {
    addToast('성공적으로 저장되었습니다!', 'success');
  };

  return <button onClick={handleClick}>토스트 띄우기</button>;
};

export default DemoButton;

4. 마무리

위 방식으로 React 애플리케이션에 쉽게 Toast 시스템을 도입할 수 있습니다. Context와 상태 관리를 이용해 간결하지만 확장 가능한 구조를 만들 수 있으며, 필요 시 애니메이션, 커스텀 컴포넌트, 위치 변경 등을 추가 구현하면 더욱 고급스러운 UX를 만들 수 있습니다.