user3352042
user3352042

Reputation: 131

React Proper useEffect dependencies

So I have this app which has about 6 fetch function for different api endpoints, and I'm getting a warning error at my terminal - the same function names saying that i should include it in the dependency array of my useEffect. my functions are above the useEffects. the process is on first load I want them to fetch all, and then only fetches again if they pick another source or type - its doing the job that i want but why am I seeing these warnings?

useEffect(() => {

    fetchTtype()
    fetchSource()
    fetchSet()
}, [chosenType, chosenSource])

useEffect(() => {
    setIsLoading(true)
    fetchUsers()
    fetchUserProblems()
    fetchAuthority()
},[])

Line 111:8: React Hook useEffect has missing dependencies: 'fetchData', 'fetchSource', and 'fetchType'. Either include them or remove the dependency array
react-hooks/exhaustive-deps Line 118:7: React Hook useEffect has missing dependencies: 'fetchProblems', 'fetchAuthority', 'fetchUsers', and 'setIsLoading'. Either include them or remove the dependency array react-hooks/exhaustive-deps

Upvotes: 0

Views: 2513

Answers (2)

Prabadhya Upadhyay
Prabadhya Upadhyay

Reputation: 11

If your functions or methods are going to be called only for one time then it's better to declare and invoke the function in the same useEffect hook.

For Example:-

 useEffect(() => {
    const options = {
      weekday: "long",
      year: "numeric",
      month: "long",
      day: "numeric",
    };
    const getCurrentDate = () => {
      let date = new Date();
      setDate(date.toLocaleDateString("en-us", options));
    };

    getCurrentDate();
  }, []);

As the above code shows try to include the functions or methods inside your useEffect hook or else if you want to try to add some dependency which can be variable that when that changes your useEffect will trigger again.

Upvotes: 1

Tehila
Tehila

Reputation: 1102

If you use inside your useEffect some functions/variables that are declared outside of the useEffect , then you would have to add it as a dependency in case it might change.

External variables that are used inside of useEffect should be inculded in the dependency array, and your functions are defined outside of it, so that's the reason it's warning you.

Though there are some exceptional cases when you don't have to add everything. For example, if you call setState method inside useEffect, it doesn't have to be inculded in the dependency array (because React will make sure this function won't change).

Read more about what to add to the dependencies here: https://devtrium.com/posts/dependency-arrays

Upvotes: 3

Related Questions