score:283
By default mapDispatchToProps
is just dispatch => ({ dispatch })
.
So if you don't specify the second argument to connect()
, you'll get dispatch
injected as a prop in your component.
If you pass a custom function to mapDispatchToProps
, you can do anything with the function.
A few examples:
// inject onClick
function mapDispatchToProps(dispatch) {
return {
onClick: () => dispatch(increment())
};
}
// inject onClick *and* dispatch
function mapDispatchToProps(dispatch) {
return {
dispatch,
onClick: () => dispatch(increment())
};
}
To save you some typing Redux provides bindActionCreators()
that lets you turn this:
// injects onPlusClick, onMinusClick
function mapDispatchToProps(dispatch) {
return {
onPlusClick: () => dispatch(increment()),
onMinusClick: () => dispatch(decrement())
};
}
into this:
import { bindActionCreators } from 'redux';
// injects onPlusClick, onMinusClick
function mapDispatchToProps(dispatch) {
return bindActionCreators({
onPlusClick: increment,
onMinusClick: decrement
}, dispatch);
}
or even shorter when prop names match action creator names:
// injects increment and decrement
function mapDispatchToProps(dispatch) {
return bindActionCreators({ increment, decrement }, dispatch);
}
If you'd like you can definitely add dispatch
there by hand:
// injects increment, decrement, and dispatch itself
function mapDispatchToProps(dispatch) {
return {
...bindActionCreators({ increment, decrement }), // es7 spread syntax
dispatch
};
}
There's no official advise on whether you should do this or not. connect()
usually serves as the boundary between Redux-aware and Redux-unaware components. This is why we usually feel that it doesn't make sense to inject both bound action creators and dispatch
. But if you feel like you need to do this, feel free to.
Finally, the pattern you are using right now is a shortcut that's even shorter than calling bindActionCreators
. When all you do is return bindActionCreators
, you can omit the call so instead of doing this:
// injects increment and decrement
function mapDispatchToProps(dispatch) {
return bindActionCreators({ increment, decrement }, dispatch);
}
export default connect(
mapStateToProps,
mapDispatchToProps
)(App);
can be written as this
export default connect(
mapStateToProps,
{ increment, decrement } // injects increment and decrement
)(App);
However you'll have to give up that nice short syntax whenever you want something more custom, like passing dispatch
as well.
score:2
While you could pass dispatch
down as part of dispatchToProps
, I would recommend avoiding accessing the store
or dispatch
directly from within your components. It seems like you would be better served by passing in a bound action creator in connect's 2nd argument dispatchToProps
See an example I posted here https://stackoverflow.com/a/34455431/2644281 of how to pass down an "already bound action creator" this way your components don't need to directly know about or depend on the store/dispatch.
Sorry to be brief. I'll update w/ more info.
score:7
You can usually mix and match based on what you'd like.
You can pass dispatch
on as a prop if that is what you want:
export default connect(mapStateToProps, (dispatch) => ({
...bindActionCreators({fetchUsers}, dispatch), dispatch
}))(Users);
I'm not sure how fetchUsers
is used (as an async function?), but you would usually use something like bindActionCreators
to auto-bind dispatch and then you would not have to worry about using dispatch
directly in connected components.
Using dispatch
directory sort of couples the dumb, stateless component with redux. Which can make it less portable.
Source: stackoverflow.com
Related Query
- How to get simple dispatch from this.props using connect w/ Redux?
- How to connect simple Formik form with Redux store and dispatch an action?
- Where does the root reducer come from in this redux react example and how does dispatch knows which reducer to go?
- How to pass props from container component to redux form(component) - react using typescript
- How to get access to a specific reducer variables as props from react without using routes
- How to get reference to the dispatch method from a component method in my react-native redux app
- How to get updated state from Redux store using redux-toolkit after component has already rendered?
- In a Functional Component, how do you access props from the redux store using react-redux connect?
- How to get the data from Redux store using class components in React
- How to get ReactRouter Props , while using Redux
- How do I get the updated state from Redux using useEffect
- How to get specific fields from an api fetch using redux saga
- How to get data using redux from api?
- How can I access my dispatch routines from my props using TypeScript + Redux?
- How to get classname or props from NavLink to use with google tag manager with react and redux in a stateless functional component?
- How to dispatch a props from a button with React Redux
- How to add action from redux connect to component props typescript
- how to get min or max dates from a list of dates using moment.js?
- How to get values from input types using this.refs in reactjs?
- How to dispatch Redux action from stateless component when route is loaded?
- How to reset state of Redux Store when using configureStore from @reduxjs/toolkit?
- Javascript Redux - how to get an element from store by id
- How to connect to redux store from react-router onEnter hook?
- React Redux - How to dispatch an action on componentDidMount when using mapDispatchToProps in a connected component
- How to execute store.unsubscribe from useEffect using React hooks and Redux
- How to get param from url in getStaticProps without using getStaticPaths?
- How do I change props from a child component using hooks?
- How to get dispatch redux
- How to get Metadata from a Token adress using web3 js on SOLANA
- How do I access data returned from an axios get to display on a web page using react js?
More Query from same tag
- How to rewrite the protected/private route using TypeScript and React-Router 4, 5 or 6?
- React propTypes: objectOf vs shape?
- Spring Boot with ReactJS
- When I first click the delete button, all the notes are disappeared but, when I refresh the page it works just fine
- How can you an the values of a selector into an empty string?
- React Router in Laravel
- Using gulp/webpack and getting unexpected token error with spread operator
- Get the Category ID of a button in React
- TypeError: this.props.persistor.subscribe is not a function Redux Persist
- CSS Flexbox - How to make flex item shrink to fit flex container?
- Which is the best Practice for localisation ? By Using DB along with cache or Property file kept outside the war
- React Testing Library: Detecting Input Pattern Rejection
- How to pass props to a component mapped from an array of components?
- Why is there an error on createSlice when the initial state is null?
- remove class from all other elements when adding class
- How to use onchange with autocomplete material ui?
- CKEditorError: Cannot read property 'name' of undefined
- How to use spread operator to delete an object from array of objects using spread operator using react?
- React svg image
- How to display UPDATE results immediatly
- How to integrate AbortController with Axios and React?
- object didnt get passed to another method (React)
- Access Inline SVG
- Add transition to collapsable div using styled-components in React
- this.props returns undefined with array.map((item, i)
- Pass component as a prop in Reactjs
- Get SVG icons dynamically in Next.js
- How to make the image box under the button in React
- Are custom hooks special functions like Function Components w.r.t. hooks?
- Count length properties of each object.entry