Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hot Reload not working properly with React-Redux and Hooks

I'm trying to get hot reloading to work with react 16.9.0 and react-redux 7.1.1.

This is my code where I want the loading of data (callback in useEffect()) called only once:

function Sidebar() {
  const dispatch = useCallback(useDispatch(), []);
  useEffect(() => {
    console.info('useEffect');
    dispatch(loadFields());
  }, [dispatch]);

  ...
}

Despite using useCallback() to memoize the function, when I save a change to another JS file, the callback in useEffect() gets called again, reloading the fields.

If I changed the dependency of the useEffect() function from [dispatch] to just [], however, then it works the way I want and the callback in useEffect() does not get called on hot reload. But if I do this, the recommended React Eslint complains that I didn't include the dispatch dependency.

How do I make the linter happy, while getting hot reloading to work properly with useDispatch()?

Other symptoms:

  • Using a static ['anything'] also results in hot reloading not working; which is strange, because it should be equivalent to [].
like image 359
Attila Szeremi Avatar asked Nov 24 '25 13:11

Attila Szeremi


1 Answers

It turns out that I had the wrong idea about hot reloading hooks.

https://github.com/gaearon/react-hot-loader/tree/v4.12.15#hook-support

It was precisely that there was any dependency for useEffect() that caused successful hot reloads, because it is actually rerunning the hooks which makes the hot reload successful, not not running them.

This is to allow you to make changes inside useEffect() and have those changes applied by rerunning just your hook without having to refresh the whole page. As long as you are not using [] as your hook dependencies. Of course the side effect is that if you don't make changes to your useEffect() it will still rerun it, which is just somewhat inconvenient.

So basically if I want a hook to not rerun on any code change in the project, I need to make the hook dependencies [].

But as a trade-off the hook won't rerun even if I make a code change inside of it; and of course another trade-off is that it makes the react-hooks/exhaustive-deps eslint rule unhappy.

like image 179
Attila Szeremi Avatar answered Nov 27 '25 04:11

Attila Szeremi



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!