Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fix React Redux and React Hook useEffect has a missing dependency: 'dispatch'

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

I use useDispatch() Hook from React Redux on a functional component like this:

const Component = () => {
  const dispatch = useDispatch();
  const userName = useSelect(state => state.user.name);

  useEffect(() => {
    dispatch(getUserInformation());
  }, [userId]);

  return (
    <div>Hello {userName}</div>
  );
};

export default Component;

How to remove this warning without removing the dependency array react-hooks/exhaustive-deps which can be useful to avoid other errors.

like image 257
Ignacio Avatar asked Jan 26 '23 08:01

Ignacio


1 Answers

To avoid that warning simply add dispatch to the dependency array. That will not invoke re-renders because dispatch value will not change.

const Component = () => {
  const dispatch = useDispatch();
  const userName = useSelect(state => state.user.name);

  useEffect(() => {
    dispatch(getUserInformation());
  }, [userId, dispatch]);

  return (
    <div>Hello {userName}</div>
  );
};

export default Component;
like image 200
Muhammad Zeeshan Avatar answered Jan 29 '23 21:01

Muhammad Zeeshan