Reputation: 1642
Is there anything wrong with using useEffect in this way? A lot of examples that I have seen seem to put the function definition inside useEffect as well. However, I want to be able to call the function again after an item is deleted/updated.
const getSchools = async () => {
const data = await getDocs(schoolsCollectionRef)
setSchools(data.docs.map((doc) => ({...doc.data(), id:doc.id})))
console.log(data.docs)
}
useEffect(() =>{
getSchools()
}, [])
Upvotes: 3
Views: 774
Reputation: 28654
is there anything wrong with using useEffect in this way?
Well there could be. In general, the advice is to list all variables (from component scope) that you use inside your useEffect
, as dependencies. In your case getSchools
is such a variable (even though it is a function - the function itself could be referencing some variables from component scope, and that could lead to stale closures). There is a section about this in the official docs, which you can check.
Since you can't move getSchools
inside useEffect
(because you use it elsewhere), I think you can go with this solution:
As a last resort, you can add a function to effect dependencies but wrap its definition into the useCallback Hook
Also from the docs here is case when you can omit the function from dependencies:
It is only safe to omit a function from the dependency list if nothing in it (or the functions called by it) references props, state, or values derived from them
Upvotes: 5