What are the cases where Redux dispatch could change?

后端 未结 1 872
我在风中等你
我在风中等你 2021-02-14 16:48

In react-redux v7, we now have the useDispatch() hook to get a reference to the store dispatch. See here: https://react-redux.js.org/api/hooks#usedispatch

T

1条回答
  •  深忆病人
    2021-02-14 17:21

    There's two answers to this.

    First, as far as I know, the React "rules of hooks" ESLint rule knows how to handle the built-in hooks specially. For example, it knows that useState() always returns the same setter function instance, so you don't have to include that in a useEffect() dependency array (ditto for the dispatch function from a useReducer() call).

    However, the lint rule doesn't know about custom hooks, whether they be from a library or your own. So, since useDispatch() is a custom hook, the lint rule has to assume that whatever this dispatch thing is could change, and tries to tell you that you need to list it as a dependency.

    The second answer is that it's possible to pass a new store reference to , in which case there's a different store.dispatch being returned from the useDispatch() hook.

    So, realistically, the code will run fine without including dispatch in the deps array, because your app is almost definitely using the same store instance the entire time. But, since the lint rule doesn't know that, you will probably need to include it in the list anyway to make it be quiet.

    (Source: I'm a Redux maintainer, and helped guide the implementation of our hooks API :) )

    0 讨论(0)
提交回复
热议问题