useDIspatch vs old style dispatchers

I am used to defining my own dispatchers, passing them to mapDispatchToProps, and using them to update a redux store.

It confuses me how useDispatch works. How does it know what reducer to dispatch an action to? How many arguments can be passed to it, since I never define that myself?

It’s exactly the same, it gives you the dispatch function, with which you can do anything you like, same as in mapDispatchToProps. It just uses hooks to tap into context rather than a higher-order component – useDispatch rather than <Connect> with your dispatch stuff defined in an object. It had to be done the latter way when react-redux was first written because hooks didn’t exist (react-redux has always used the context API, but it had to be accessed via Connect)

Umm, I can remember thinking this when I first encountered it, but this is a basic misunderstanding of how Redux works, It’s much, much simpler than that

It doesn’t “know” what reducer to dispatch it to. It doesn’t need to because there is only ever one reducer and you dispatch messages to it. It’s just a big switch statement that you send events to:

  • dispatch({ type: “DO_A_THING” })`
  • { type: "DO_A_THING" }, goes into the switch statement,
  • switch checks the type,
  • picks the branch that matches “DO_A_THING”,
  • returns updated state
  • in react-redux, useSelector is going to keep in sync with the redux state and trigger a rerender when the values you are interested in change

For convenience, you write the functions to update slices of state (the “reducers”) separately, but they just get jammed together into one big switch statement. It makes no difference where you send those messages from in the app (where you dispatch an action) or what reducer function you’ve defined for a specific slice of state, all the store does is take whatever gets dispatched and passes it into that one big function

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.