Aniket Deshpande
Aniket Deshpande

Reputation: 306

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

can anyone help me to get rid of this warning

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

here is my code

function Register(props) {
  const inusers=useSelector( (state) => {return state});
  const history=useHistory()
  const dispatch=useDispatch();
  // const formik = useFormikContext();


  useEffect( () => {
    dispatch(fetchUser())
  },[])

Upvotes: 13

Views: 22143

Answers (2)

Andrea Costanzo
Andrea Costanzo

Reputation: 2235

Just add dispatch among the dependencies:

  useEffect(() => {
       dispatch(fetchUser())
  },[dispatch])

Dispatch is a safe dependency to add and it won't cause infinite loops. For more insights on why dispatch can change (and when it can change) check:

What are the cases where Redux dispatch could change?

UPDATE: from react-redux documentation

https://react-redux.js.org/api/hooks

Upvotes: 26

Ferin Patel
Ferin Patel

Reputation: 3998

You can write comment above useEffect dependency eslint-disable-next-line react-hooks/exhaustive-deps and it will stop complaining.

React guarantees that dispatch function identity is stable and won’t change on re-renders. This is why it’s safe to omit from the useEffect or useCallback dependency list.

So its safe to ignore this warning.

function Register(props) {
  const inusers=useSelector( (state) => {return state});
  const history=useHistory()
  const dispatch=useDispatch();
  // const formik = useFormikContext();


  useEffect( () => {
    dispatch(fetchUser())

    // eslint-disable-next-line react-hooks/exhaustive-deps
  },[])

Upvotes: 3

Related Questions