Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling dispatch in useEffect?

At the moment I am simple calling it inside the useEffect hook, without having it as a dependency as I only want it to run once. This however gives React Hook useEffect has a missing dependency: 'dispatch'. Should I add dispatch to the dependencies or is there a better practice for this?

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

like image 1000
HeyMan12388 Avatar asked Apr 08 '26 11:04

HeyMan12388


1 Answers

The dispatch function doesn't change between re-renders. The eslint warning isn't aware of what each function does and whether or not it will be recreated or not and hence it shows the warning to prompt the user if he/she has missed something

You can safely disable the warning in this case and not include dispatch as a dependency

  useEffect(() => {
    dispatch(handleGetUser());

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

Even if you include dispatch as a dependency you will not see side-effects as dispatch will not change unless the library exposing it has a bug

like image 181
Shubham Khatri Avatar answered Apr 13 '26 11:04

Shubham Khatri



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!