실시간 변경 수신하기
Realtime Database 이벤트를 구독하고 값과 하위 항목의 변경에 즉시 반응하며 메모리 누수를 방지하도록 수신기를 정리하여 앱을 진정한 실시간 앱으로 만듭니다.
실시간 변경 수신하기은(는) CoddyKit의 무료 Firebase Auth & Realtime Database Apps 강의입니다. 이것은 4개 중 4번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Firebase Auth & Realtime Database Apps 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Firebase Auth & Realtime Database Apps 강의에는 총 4개의 강의가 포함되어 있습니다.
이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.
From Fetch to Stream
Reading data once gives you a snapshot. The power of Realtime Database is live updates: your app reacts the instant data changes on the server, with no polling.
This is done by attaching listeners to a location in the database.
The Value Event
The most common listener is value. It fires once immediately with current data, then again every time anything under that location changes.
import { getDatabase, ref, onValue } from 'firebase/database';
const db = getDatabase();
onValue(ref(db, 'scores/global'), (snapshot) => {
console.log('New value:', snapshot.val());
});Reading the Snapshot
The callback receives a DataSnapshot. Use .val() for the data, .exists() to check presence, and .key for the node name.
onValue(ref(db, 'user/42'), (snap) => {
if (snap.exists()) {
console.log(snap.key, snap.val());
}
});Child Events
For lists, value events resend the whole node on every change. Child events are more efficient, firing per item:
onChildAddedonChildChangedonChildRemoved
Using onChildAdded
onChildAdded fires once for each existing child, then for every new one. It is perfect for chat messages or feeds.
import { onChildAdded } from 'firebase/database';
onChildAdded(ref(db, 'messages'), (snap) => {
appendMessage(snap.key, snap.val());
});Reacting to Changes and Removals
Pair additions with change and removal handlers to keep your UI in sync without re-rendering everything.
import { onChildChanged, onChildRemoved } from 'firebase/database';
onChildChanged(ref(db, 'messages'), s => updateMessage(s.key, s.val()));
onChildRemoved(ref(db, 'messages'), s => removeMessage(s.key));Reading Once
Sometimes you want current data without an ongoing subscription. Use get for a one-time read instead of a listener.
import { get } from 'firebase/database';
const snap = await get(ref(db, 'config'));
console.log(snap.val());Detaching Listeners
Listeners stay active until removed, consuming bandwidth and memory. Always detach them when a screen unmounts, using the unsubscribe function returned by onValue.
const unsubscribe = onValue(ref(db, 'scores'), cb);
// later, when leaving the screen:
unsubscribe();Handling Errors
Listeners can fail, often due to Security Rules denying read access. Provide an error callback so failures are visible, not silent.
onValue(ref(db, 'private'), (snap) => render(snap), (error) => {
console.error('Read failed:', error.message);
});Performance Tips
Keep listeners efficient:
- Listen at the smallest path that has the data you need
- Prefer child events for large lists
- Never attach a value listener to the database root
A Live Counter Example
Putting it together: attach a value listener to a counter node, update the DOM in the callback, and unsubscribe on cleanup. The number changes for every connected client in real time.
const unsub = onValue(ref(db, 'visitors/count'), (snap) => {
document.getElementById('count').textContent = snap.val() ?? 0;
});Quick Check
Test your understanding of realtime listeners.
Recap
Your app can now respond to data the moment it changes.
- Use
onValuefor single nodes - Use child events for efficient lists
- Read once with
getwhen no subscription is needed - Always detach listeners and handle errors
- Listen at the narrowest useful path
자주 묻는 질문
“실시간 변경 수신하기” 강의는 무료인가요?
네 — “실시간 변경 수신하기” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Firebase Auth & Realtime Database Apps 강의 전체를 잠금 해제할 수 있습니다. Firebase Auth & Realtime Database Apps 강의에는 총 4개의 강의가 포함되어 있습니다.
“실시간 변경 수신하기”에서 뭘 배우나요?
Realtime Database 이벤트를 구독하고 값과 하위 항목의 변경에 즉시 반응하며 메모리 누수를 방지하도록 수신기를 정리하여 앱을 진정한 실시간 앱으로 만듭니다. 브라우저에서 직접 실행하는 실습 코드로 Firebase Auth & Realtime Database Apps을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
Firebase Auth & Realtime Database Apps을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 Firebase Auth & Realtime Database Apps은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 4번째 강의입니다.
“실시간 변경 수신하기” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 Firebase Auth & Realtime Database Apps 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 Firebase Auth & Realtime Database Apps 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- 실시간 데이터베이스 기초
- 데이터 읽기 및 쓰기
- 데이터 구조화하기
- 실시간 변경 수신하기