The best way to access your store through a component is using the connect() function, as described in the documentation. This allows you to map state and action creators to your component, and have them passed in automatically as your store updates. Additionally, by default it will pass in dispatch as this.props.dispatch. Here's an example from the docs:
import { connect } from 'react-redux'
import { setVisibilityFilter } from '../actions'
import Link from '../components/Link'
const mapStateToProps = (state, ownProps) => {
return {
active: ownProps.filter === state.visibilityFilter
}
}
const mapDispatchToProps = (dispatch, ownProps) => {
return {
onClick: () => {
dispatch(setVisibilityFilter(ownProps.filter))
}
}
}
const FilterLink = connect(
mapStateToProps,
mapDispatchToProps
)(Link)
export default FilterLink
Note that connect actually creates a new component that wraps around your existing one! This pattern is called Higher-Order Components, and is generally the preferred way of extending a component's functionality in React (over stuff like inheritance or mixins).
Due to it having quite a few performance optimizations and generally being less likely to cause bugs, the Redux devs almost always recommend using connect over accessing the store directly - however, if you have a very good reason to need lower level access, the Provider component makes it so all its children can access the store through this.context:
class MyComponent {
someMethod() {
doSomethingWith(this.context.store);
}
}
connectis the best/most reliable way to do it, unless you have a very good reason to go lower level (the guide mentions thatconnecthas extra performance optimizations). That said, if you really want to access the store directly,Providermakes it so all child components can do so via the context -this.context.storeinside your component should return this instance. - Joe Clayconnect()without wrapping the root component in<Provider>. - lngs