DEV Community

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

Posted on

2 1

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

AWS GenAI LIVE image

How is generative AI increasing efficiency?

Join AWS GenAI LIVE! to find out how gen AI is reshaping productivity, streamlining processes, and driving innovation.

Learn more

Top comments (0)

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

πŸ‘‹ Kindness is contagious

Please leave a ❀️ or a friendly comment on this post if you found it helpful!

Okay