Last active
January 5, 2021 16:13
-
-
Save MorenoMdz/3622221a54a6b0a5985084a056876927 to your computer and use it in GitHub Desktop.
React Firebase useEffect cleanup example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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