DEV Community

Cover image for Building Real-Time Features with Firebase (or Supabase) in React Native
Saad Mehmood
Saad Mehmood

Posted on

Building Real-Time Features with Firebase (or Supabase) in React Native

Real-time updates—chat, live data, presence—are common in mobile apps. Here’s how I approach them with Firebase or Supabase in React Native.

Why Firebase or Supabase?

Both give you:

  • Realtime listeners — Subscribe to a path or query; get updates when data changes.
  • Auth — So you can secure data per user.
  • Offline — Firebase has built-in persistence; Supabase can work with local SQLite or similar.

I use Firebase when the team already uses it or needs other Google services; Supabase when we want Postgres and a more SQL-friendly API.

Firebase Firestore: Realtime Listeners

// Subscribe to a collection or query
const unsubscribe = firestore()
  .collection('chats')
  .doc(chatId)
  .collection('messages')
  .orderBy('createdAt', 'desc')
  .limit(50)
  .onSnapshot(
    (snapshot) => {
      const messages = snapshot.docs.map(doc => ({
        id: doc.id,
        ...doc.data(),
      }));
      setMessages(messages);
    },
    (error) => {
      // Handle errors, show user-friendly message
    }
  );

// Cleanup on unmount
return () => unsubscribe();
Enter fullscreen mode Exit fullscreen mode

Tips:

  • Use limit() and paginate; don’t load entire collections.
  • Enable offline persistence so the app works without network.
  • Secure with Firestore rules: validate request.auth and restrict reads/writes by user or role.

Supabase: Realtime with Postgres

const channel = supabase
  .channel('messages')
  .on(
    'postgres_changes',
    {
      event: 'INSERT',
      schema: 'public',
      table: 'messages',
      filter: `chat_id=eq.${chatId}`,
    },
    (payload) => {
      setMessages(prev => [payload.new, ...prev]);
    }
  )
  .subscribe();

return () => {
  supabase.removeChannel(channel);
};
Enter fullscreen mode Exit fullscreen mode

You get realtime from Postgres changes (insert/update/delete). Enable Realtime on the tables you need in the Supabase dashboard.

Auth First

Both platforms tie data to users. Ensure:

  • User is signed in before subscribing.
  • Listeners are scoped to the current user (e.g. userId in the path or filter).
  • On auth state change, unsubscribe from old listeners and subscribe with the new user.

Offline and UX

  • Show a “connecting” or “offline” indicator when the client is disconnected.
  • Queue critical actions (e.g. send message) and retry when back online.
  • For Firebase, use persistence; for Supabase, consider local caching (e.g. React Query + persistence) for a smooth offline experience.

Real-time doesn’t have to mean “complex.” Start with one collection or table, get the listener and cleanup right, then expand from there.


Saad Mehmood — Portfolio

Top comments (0)