DEV Community

Cover image for React Native Firestore: Real-time update with custom hook
Swee Sen
Swee Sen

Posted on

React Native Firestore: Real-time update with custom hook

Supposed that we want to observe real-time changes of a particular Firestore document, we could implement the logic in a custom hook and reuse the logic across many components:

export function useUserInfo() {
  const [user, setUser] = useState<User | undefined>();

  useEffect(() => {
    const unsubscribe = subscribeFirestoreUser();
    return () => unsubscribe();
  }, []);

  const subscribeFirestoreUser = () => {
    const subscriber = firestore()
      .collection(FIRESTORE_COLLECTIONS.USER)
      .doc(userId) // an example id here
      .onSnapshot(documentSnapshot => {
        setUser(documentSnapshot.data() as User);
      });
    return subscriber;
  };

  return {
    user,
  };
}
Enter fullscreen mode Exit fullscreen mode

To use the user information in other components:

export default function HomePage() {

  const { user } = useUserInfo();

  return <Text>{user.name}</Text>;
}

Enter fullscreen mode Exit fullscreen mode

Top comments (0)