Component - Realtime Database
This component shows how a React Native app connects to a Realtime Database to display live data updates. It listens for changes and updates the UI instantly, like seeing new chat messages appear without refreshing.
This component shows how a React Native app connects to a Realtime Database to display live data updates. It listens for changes and updates the UI instantly, like seeing new chat messages appear without refreshing.
View ├─ Text (Title) ├─ FlatList (Data List) │ └─ Text (List Item) └─ Button (Refresh)
on('value') in React Native with Realtime Database?on('value') methodon('value') listens for updates [OK]database() returns the database instance, and ref('path') creates a reference.database().ref('users') which is correct. const usersRef = database.ref('users'); misses parentheses after database. const usersRef = database().reference('users'); uses a wrong method name. const usersRef = database().child('users'); uses child which is valid but requires a reference first.database().ref('path') for references [OK]const messagesRef = database().ref('messages');
messagesRef.on('value', snapshot => {
console.log(snapshot.val());
});snapshot.val() returnson('value') listener triggers immediately with current data and on every change, so it logs the current 'messages' data.snapshot.val() returns data [OK]const ref = database().ref('items');
ref.on('value', snapshot => {
setItems(snapshot.val());
});
// Later in component unmount
ref.off('value');off('value', callback) must be called with the same callback function used in on.off('value') without the callback, so the listener remains active, causing potential memory leaks.useEffect for setup and cleanupuseEffect, attach the listener and return a cleanup function that calls off with the same callback.on('value') listener outside the component and never remove it leaks memory. Call off('value') immediately after on('value') inside the same function removes listener immediately, so no updates. Use once('value') instead of on('value') to get live updates only fetches once, not live updates.useEffect hook to attach on('value') listener and return a cleanup function that calls off('value', callback) -> Option APass the test and this pattern moves unknown