일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | ||||
4 | 5 | 6 | 7 | 8 | 9 | 10 |
11 | 12 | 13 | 14 | 15 | 16 | 17 |
18 | 19 | 20 | 21 | 22 | 23 | 24 |
25 | 26 | 27 | 28 | 29 | 30 | 31 |
- 리액트
- 오공완
- map()에는 key값이 필요
- 리스트랜더링
- React
- 오공완 #리액트 공부 #React
- 클래스 추가하기 #특정 url 클래스 추가 #사이트 접속시 클래스 추가 #오공완 #javascript
- Today
- Total
new_bird-hyun
Next.js에서 SSE(Server-Sent Events)와 Zustand를 활용한 실시간 알림 배지 시스템 구현 본문
- SSE(Server-Sent Events)와 Zustand를 활용하여 실시간 알림 배지 표시
- 특정 이벤트가 발생할 때 클라이언트가 알림을 받고 UI를 자동 업데이트하는 방법
- 서버에서 주기적으로 새로운 알림을 전송하고, 클라이언트에서 알림 개수를 표시하는 UI 구현
npm install zustand
store/useNotificationStore.js (Zustand 전역 상태)
import { create } from 'zustand';
const useNotificationStore = create((set) => ({
notifications: [],
unreadCount: 0,
addNotification: (notif) =>
set((state) => ({
notifications: [...state.notifications, notif],
unreadCount: state.unreadCount + 1,
})),
markAllRead: () => set({ unreadCount: 0 }),
}));
export default useNotificationStore;
pages/api/notifications.js (SSE 알림 API)
export default function handler(req, res) {
res.setHeader('Content-Type', 'text/event-stream');
res.setHeader('Cache-Control', 'no-cache');
res.setHeader('Connection', 'keep-alive');
const sendNotification = (message) => {
res.write(`data: ${JSON.stringify({ message, time: new Date().toLocaleTimeString() })}\n\n`);
};
sendNotification('새로운 알림 시스템이 시작되었습니다.');
const interval = setInterval(() => {
sendNotification(`새로운 이벤트 발생!`);
}, 7000);
req.on('close', () => {
clearInterval(interval);
});
}
components/NotificationBadge.js (알림 배지 UI)
'use client';
import { useEffect } from 'react';
import useNotificationStore from '../store/useNotificationStore';
export default function NotificationBadge() {
const { unreadCount, addNotification, markAllRead } = useNotificationStore();
useEffect(() => {
const eventSource = new EventSource('/api/notifications');
eventSource.onmessage = (event) => {
addNotification(JSON.parse(event.data));
};
return () => eventSource.close();
}, [addNotification]);
return (
<div>
<h2>실시간 알림 배지</h2>
<button onClick={markAllRead}>
알림 보기 {unreadCount > 0 && <span>({unreadCount})</span>}
</button>
</div>
);
}
components/NotificationList.js (실시간 알림 UI)
'use client';
import useNotificationStore from '../store/useNotificationStore';
export default function NotificationList() {
const notifications = useNotificationStore((state) => state.notifications);
return (
<div>
<h2>알림 목록</h2>
<ul>
{notifications.map((notif, index) => (
<li key={index}>{notif.message} ({notif.time})</li>
))}
</ul>
</div>
);
}
app/page.js
import NotificationBadge from '../components/NotificationBadge';
import NotificationList from '../components/NotificationList';
export default function Home() {
return (
<div>
<NotificationBadge />
<NotificationList />
</div>
);
}
SSE와 Zustand를 활용하면 실시간 알림 배지 및 알림 UI를 쉽게 구축 가능
'코딩 공부' 카테고리의 다른 글
Web Push API에서 사용자 맞춤 알림 구독/구분/취소 기능 구현하기 (0) | 2025.03.24 |
---|---|
Next.js + Firebase Cloud Messaging(FCM) 푸시 알림을 실무에 적용할 때 고려할 점 (0) | 2025.03.22 |
Next.js에서 Server-Sent Events(SSE)와 WebSocket 비교 및 실시간 데이터 처리 (0) | 2025.03.17 |
Next.js와 WebSocket을 활용한 실시간 채팅 애플리케이션 구현 (0) | 2025.03.16 |
Next.js에서 Zustand와 SWR을 활용한 실시간 데이터 동기화 전략 (0) | 2025.03.14 |