Skip to content

Instantly share code, notes, and snippets.

@MorenoMdz
Last active January 5, 2021 16:13
Show Gist options
  • Save MorenoMdz/3622221a54a6b0a5985084a056876927 to your computer and use it in GitHub Desktop.
Save MorenoMdz/3622221a54a6b0a5985084a056876927 to your computer and use it in GitHub Desktop.
React Firebase useEffect cleanup example
import React, { useState, useEffect, useRef, useCallback } from 'react';
const mountedRef = useRef(true);
const fetchData = useCallback(async () => {
try {
// do your async call here
const ref = await db
.collection('stuff')
.where('stuff', '==', id)
.get();
const data = ref.docs.map(doc => ({ id: doc.id, ...doc.data() }));
// if it is not mounted yet/anymore, break out
if (!mountedRef.current) return null;
// then do the data set (which will trigger the rerender and could cause the leak
setRedeems(data);
setIsFetching(false);
} catch (error) {
console.log(error);
}
}, [mountedRef]);
useEffect(() => {
fetchData();
return () => {
mountedRef.current = false;
};
}, [fetchData]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment