0

My useEffect hook is running when dependency has not changed.

useEffect(() => {
   console.log('Search useEffect Run')
   dispatch(fetchSearchData(searchItem));          
 }, [dispatch, searchItem]);

searchItem is part of a Redux slice as:

const searchItem = useSelector((state) => state.posts.searchTerm);

const initialState = { posts: [], searchTerm: '', selectedSubreddit: 'r/pics/', };

The useEffect is running when searchItem is not changing from empty string.

Thanks for any help.

I have tried useCallback but getting the same issue.

This is inside a function and useEffect runs twice each time function is rendered (for a unrelated event).

Cheers

Richie
  • 13
  • 6
  • You don't have to add `dispatch` to the dependency array, the function won't change. – timotgl Aug 29 '23 at 10:50
  • If I do not add dispatch as a dependency it gives me a warning as: React Hook useEffect has a missing dependency: 'dispatch'. Either include it or remove the dependency array – Richie Aug 29 '23 at 11:44
  • Yes, the linter warning is famously wrong/overzealous in this case. See updated answer for https://stackoverflow.com/questions/56972415/useeffect-dependency-array-and-eslint-exhaustive-deps-rule – timotgl Aug 29 '23 at 17:19

1 Answers1

-1

This is because you are in useStrict mode. useStrict make your useEffect hook runs twice for debugging purpose read more about useStrict

Aslan_Z
  • 1
  • 2
  • Cheers. It runs twice on first render, then runs twice each time the function renders even though the dependency not changing. Could it be something to do with it being part of a Redux slice – Richie Aug 29 '23 at 11:43