A Realtime Database lets your app save and get data instantly. It keeps all users' data updated live without needing to refresh.
0
0
Realtime Database in React Native
Introduction
You want to show chat messages as soon as someone sends them.
You need to update a game scoreboard for all players at the same time.
You want to sync user settings across devices instantly.
You want to show live updates like stock prices or sports scores.
You want to build a collaborative app where many users edit data together.
Syntax
React Native
import database from '@react-native-firebase/database'; // To write data database().ref('/path').set({ key: 'value' }); // To read data once const snapshot = await database().ref('/path').once('value'); const data = snapshot.val(); // To listen for realtime updates const ref = database().ref('/path'); const onValueChange = ref.on('value', snapshot => { const data = snapshot.val(); // use data }); // To stop listening ref.off('value', onValueChange);
Use ref('/path') to point to the data location.
Use on('value', callback) to listen for live changes.
Examples
This saves user data at the path '/users/user1'.
React Native
database().ref('/users/user1').set({ name: 'Anna', age: 25 });
This listens to all messages and logs them whenever they change.
React Native
database().ref('/messages').on('value', snapshot => { console.log(snapshot.val()); });
This reads the settings data once without listening for changes.
React Native
const snapshot = await database().ref('/settings').once('value'); const settings = snapshot.val();
Sample App
This app shows a number from the Realtime Database and updates it live. Pressing the button adds 1 to the number for all users instantly.
React Native
import React, { useEffect, useState } from 'react'; import { View, Text, Button } from 'react-native'; import database from '@react-native-firebase/database'; export default function RealtimeExample() { const [count, setCount] = useState(0); useEffect(() => { const ref = database().ref('/counter'); const onValueChange = ref.on('value', snapshot => { setCount(snapshot.val() || 0); }); return () => ref.off('value', onValueChange); }, []); const increment = () => { database().ref('/counter').set(count + 1); }; return ( <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}> <Text style={{ fontSize: 24, marginBottom: 20 }}>Counter: {count}</Text> <Button title="Increment" onPress={increment} /> </View> ); }
OutputSuccess
Important Notes
Always remove listeners with off to avoid memory leaks.
Realtime Database works well for simple, live data syncing but may not fit complex queries.
Security rules control who can read or write data; set them carefully.
Summary
Realtime Database keeps app data synced live for all users.
Use ref to point to data and on('value') to listen for changes.
Remember to stop listeners when not needed to save resources.