maria zahid
maria zahid

Reputation: 435

Dispatch in react redux

I am new to react and redux xo my questions will sound basic.

  1. What does dispatch means? I am referring to the term dispatching an action.
  2. Why do we need mapDispatchToProps to store actions on redux? We can simply import an action and use it. I have a scenario in which I have to load data when a component is mounted.

Upvotes: 4

Views: 2752

Answers (2)

Raghudevan Shankar
Raghudevan Shankar

Reputation: 1093

From an implementation perspective, dispatch is just a method that is used to communicate with your reducers

Let say that your action looks something like this

function myAction() {
  return { type: 'MY_ACTION' }; 
}

You're trying to communicate with the reducer that responds to the action type 'MY_ACTION'

In your mapDispatchToProps you'd typically do something like this;

function mapDispatchToProps(dispatch) {
  return { actions: bindActionCreators(myActions, dispatch) }
}

Effectively, you're wrapping(binding) your actions to the dispatch method;

function bindActionCreators(actions, dispatch) {
  // this is a very trivial implementation of what bindActionCreators does

  let wrappedActions = {};
  Object.keys(actions).forEach(action => 
    // for every action, return a function that calls dispatch on the result of what your action returns
    return function(...args) {
      // remember here that dispatch is the only way you can communicate with the reducers and you're action's type will determine which reducer responds to return the new state
      return dispatch(actions[action](..args));
    }
  );
}

And so, these "bound" actions are now assigned to a props.actions in your component.

Upvotes: 1

Win
Win

Reputation: 5584

@mariazahid mapDispatchToProps will bind the action to your component so that you can pass it down to your presentation components. This is a pattern that is normally used within using Redux with React.

You can import your action and just dispatch the action, but in most scenarios a container -> component pattern is used. A container is where the actions are mapped to and the state and the only goal of this component is to pass this data down to components that are used for presenting that data.

When working in teams, it's a pattern that is easily adoptable. Instead of importing actions from left right and center, you will just have to be aware of the container and how it passes the required actions/data down to the children.

Upvotes: 1

Related Questions