Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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())
  },[])
like image 945
Aniket Deshpande Avatar asked Feb 19 '26 11:02

Aniket Deshpande


2 Answers

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

like image 188
Andrea Costanzo Avatar answered Feb 21 '26 13:02

Andrea Costanzo


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
  },[])
like image 37
Ferin Patel Avatar answered Feb 21 '26 15:02

Ferin Patel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!