Home > Mobile >  React Hook useEffect has a missing dependency for empty array dependency
React Hook useEffect has a missing dependency for empty array dependency

Time:06-09

I am getting missing dependency warning.

React Hook useEffect has a missing dependency: 'fetchFeatured'. Either include it or remove the dependency array

My Code

useEffect(() => {
        const fetchFeatured = () => {
            onSnapshot(faeturedCollectionRef, (snapshot) =>
                setFeatured(snapshot.docs.map((doc) => ({ ...doc.data(), id: doc.id })))
            )
        }
        fetchFeatured();
    }, [])

I have used empty array for avoiding loop.

CodePudding user response:

The main purpose of the this warning is to prevent the developers from missing dependencies inside their effect and lost some behavior or unintended effect. In this case, you can

  1. Just ignore it.
  2. Suppress that rule for the entire project: Go to .eslintrc file and change 'react-hooks/exhaustive-deps': 'warn' to 'react-hooks/exhaustive-deps': 'off'
  3. Supress the rule only in this instance:
useEffect(() => {
    const fetchFeatured = () => {
        onSnapshot(faeturedCollectionRef, (snapshot) =>
            setFeatured(snapshot.docs.map((doc) => ({ ...doc.data(), id: doc.id })))
            )
        }
        fetchFeatured();
// eslint-disable-line react-hooks/exhaustive-deps
}, [])

CodePudding user response:

you can avoid the waring by doing this

 useEffect(() => {
    const fetchFeatured = () => {
        onSnapshot(faeturedCollectionRef, (snapshot) =>
            setFeatured(snapshot.docs.map((doc) => ({ ...doc.data(), id: doc.id })))
        )
    }
    fetchFeatured();
   // eslint-disable-next-line react-hooks/exhaustive-deps

}, [])

CodePudding user response:

useEffect(() => {
onSnapshot(faeturedCollectionRef, (snapshot) =>
setFeatured(snapshot.docs.map((doc) => ({ ...doc.data(), id: doc.id }))))

    }, [])

remove the function no need to have it inside of one and just have it run the firebase subscription when the useEffect fires. Now if setFeatured is being passed in as a prop or being set inside of context etc, then the dependency is unavoidable and you will have to include it inside of the array. There will be no loop etc though

  • Related