Home > database >  React useEffect depedencies warning eslint
React useEffect depedencies warning eslint

Time:10-02

I'm trying to run a function inside useEffect,My code was work perfectly but I got a warning from eslint.

const {
    error: { setErrorHolder },
  } = useNotification();

  useEffect(() => {
    if (process.env.NODE_ENV === "production") {
      setErrorHolder({ statusCode: 404, isAppError: true });
    }
  }, []);

enter image description here

In this example, I use the ReactQuery library for fetching.

const { refetch } = useQuery('example');

  useEffect(() => {
    refetch();
  }, []);

enter image description here

Is there a better solution for this case? Thank you.

CodePudding user response:

You call refetch inside useEffect. That causes eslint (Rule of hooks) raises the issue since eslint doesn't know that "refetch" is never change.

To fixed:

  • simply, add refetch to dependencies array as the suggestion
  • if you're sure that "refetch" is never change source, just disable eslint rule using the syntax
useEffect(...your effect...,
// eslint-disable-next-line react-hooks/exhaustive-deps
[])

CodePudding user response:

The solution is to add the dependency to the array you pass to useEffect.

useEffect(() => {
  if (process.env.NODE_ENV === "production") {
    setErrorHolder({ statusCode: 404, isAppError: true });
  }
}, [setErrorHolder]);
useEffect(() => {
  refetch();
}, [refetch]);
  • Related