-1

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

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131

2 Answers2

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.

Mantas Astra
  • 952
  • 6
  • 14
-1

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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
RAJENDIRAN
  • 27
  • 7
  • "The useEffect method is called for each render with the second argument being empty" this is *dead wrong*. If you have an empty dependency array it will run **once**, on the *initial render*. The danger with not having exhaustive deps is not too *many* renders but too *few*. – Jared Smith Apr 07 '22 at 12:35