Attila Szeremi
Attila Szeremi

Reputation: 5488

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:

Upvotes: 3

Views: 2615

Answers (1)

Attila Szeremi
Attila Szeremi

Reputation: 5488

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.

Upvotes: 3

Related Questions