'Use effect function in React says to import while it ends up working fine [duplicate]

Code highlighted in GitHub

useEffect(() => {
  async function getTok() {
    await Gettestimon();
    alldoc.map(forget => console.log(forget.name));
    setcondi(true);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }
  getTok();
}, []);

Whenever I compile the highlighted code, it says my function gettestimon which stands for getting a testimonial, not something else, is not imported in effect's, but then it ends up working anyway. I would like to know how to fix this, but I read somewhere and added:

// eslint-disable-next-line react-hooks/exhaustive-deps

How can I fix this?

The exact error is:

React Hook useEffect has a missing dependency: 'Gettestimon'. Either include it or remove the dependency array.eslintreact-hooks/exhaustive-deps

This is the website where it is used:

https://www.aayushgarg.net/testimonials



Solution 1:[1]

If you are using external functions/variables inside React.useEffect, you need to add them to its dependency array as well. This way, React will know to run the React.useEffect only when the values specified in the dependency array changes. Plus, you won't need to use the eslint comment.

While it still works without adding it to the dependencies array, it will decrease the performance of your component with too many unnecessary re-renders.

You could improve it to something like this

useEffect(() => {
  async function getTok() {
    await Gettestimon();
    alldoc.map(forget => console.log(forget.name));
    setcondi(true);
  }
  getTok();
}, [Gettestimon]);

To learn more about the React.useEffect, I'd suggest reading their official documentation here.

Solution 2:[2]

This is due to a missing dependency.

The useEffect method is called for each render with the second argument being empty. But if you need your useEffect function to execute when only something changes, we need to add that variable or object to the dependency array.

In using Effect, you used external objects out of function scope like alldoc and Gettestimon.

If you want to execute useEffect only with these object changes, alldoc and Gettestimo, you need to add it in the dependency array. Otherwise, you will send up in executing useEffect for each render cycle.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Mantas Astra
Solution 2 Peter Mortensen