Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the use of mapDispatchToProps when we can just use this.props.dispatch to dispatch action

Tags:

reactjs

redux

I've been using @connect annotation for some time and decide to switch to mapStateToProps and mapDispatchToProps.

I can mapStateToProps to map store to component's props fine but wondering what's the point of mapDispatchToProps when I can just call this.props.dispatch( xxx ) anywhere.

I also see some react repos and they also do not use mapDispatchToProps

  • https://github.com/Hashnode/mern-starter
  • https://github.com/andrewngu/sound-redux

Sorry if it sounds like a beginner question.

like image 558
Pongsakorn Semsuwan Avatar asked Jan 21 '17 15:01

Pongsakorn Semsuwan


People also ask

Is it possible to dispatch an action without using mapDispatchToProps?

If you do not supply your own mapDispatchToProps function or object full of action creators, the default mapDispatchToProps implementation just injects dispatch into your component's props.

Which of the following functions can be used to dispatch actions in Redux?

You can dispatch an action by directly using store. dispatch(). However, it is more likely that you access it with react-Redux helper method called connect(). You can also use bindActionCreators() method to bind many action creators with dispatch function.

What happens when we dispatch an action in Redux?

Redux uses a "one-way data flow" app structure When something happens in the app: The UI dispatches an action. The store runs the reducers, and the state is updated based on what occurred. The store notifies the UI that the state has changed.

How do you dispatch actions in a functional component?

There are two ways to dispatch actions from functional components: Using mapDispatachToProps function with connect higher order component, same as in class based components. Using useDispatch hook provided by react-redux . If you want to use this hook, then you need to import it from the react-redux package.


1 Answers

Yes, you can certainly use props.dispatch() directly in a component. However, that component now "knows" that is part of a Redux application, because it's explicitly trying to "dispatch" things.

On the other hand, if you consistently use action creator functions, now the component is just calling things like this.props.doSomeThing(). It doesn't actually "know" that it's in a Redux app, and is more reusable as a result.

I just answered a similar question at When would bindActionCreators be used in react/redux? , and wrote a longer blog post on the topic at Idiomatic Redux: Why use action creators?.

like image 137
markerikson Avatar answered Nov 15 '22 19:11

markerikson