Home > Net >  React Hook useEffect has a missing dependency: 'dispatch'. Either include it or remove the
React Hook useEffect has a missing dependency: 'dispatch'. Either include it or remove the

Time:10-19

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())
  },[])

CodePudding user response:

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
  },[])

CodePudding user response:

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:

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

  • Related