Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.
like image 867
maria zahid Avatar asked Oct 23 '25 19:10

maria zahid


2 Answers

@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.

like image 60
Win Avatar answered Oct 26 '25 10:10

Win


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.

like image 45
Raghudevan Shankar Avatar answered Oct 26 '25 11:10

Raghudevan Shankar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!