So it sounds like you’ve got a handle on Redux’s part of the workflow: where each dispatched action goes through a reducer and its return value becomes the new state. But maybe you’re struggling with where Redux ties in with React.
There are 2 pieces to that: the Provider
component, and the connect
function.
The Provider
is mostly straightforward. Wrap the root component with it, pass it the store as a prop, and you can basically forget about it after that.
The connect
function is a bit more complex, because of the higher-order function syntax and the mapStateToProps
function you need to provide, but let’s look at those. Suppose you have a component called Counter
that (a) needs data from the Redux store and/or (b) needs to be able to dispatch an action. (if neither - then don’t connect it to Redux at all)
The last line of the file will look something like this:
export default connect(mapStateToProps)(Counter)
The connect call works like this:
- The first part,
connect(mapStateToProps)
, calls connect and passes in your mapStateToProps
, and then it returns a function. That function isn’t given a name here but let’s just call it “X”.
- The second part calls that returned function with your component (think of it like
X(Counter)
). That in turn returns a new component which is the connected Counter.
The other key part to this is the mapStateToProps
function. Redux has no idea what data your component needs, so that’s the job of mapStateToProps
- to take the entire state, and pick out the pieces that you need for this specific component. It literally creates a mapping from state => props.
This one takes the whole state and picks out the count
property and passes it in as the count
prop:
function mapStateToProps(state) {
return {
count: state.count
}
}
A lot of times you’ll see this written as an arrow function instead, like this:
const mapStateToProps = state => ({
count: state.count
})
It’s more succinct but it does the same thing.
A made a youtube video a little while ago that walks through how to add Redux to a React “counter” app. It might be helpful to get the whole overview.