The answer to your question lies in how the reducer functions are generally defined, based on a couple of conventions; and how the combineReducers function works. Let's assume the following structure for your state.
{
...
posts: [...],
comments: [...],
...
}
Now when you write a reducer function, the first convention is that you would name it same as the key attribute of that part of the state which it would handle. So for the state.posts part of the state, you will have a posts reducer, and for state.comments part of the state, you will have a comments reducer.
The second convention is that these reducer functions would only accept that part of the state as an argument (along with an action, of course); that they are supposed to change. Essentially, we are explicitly passing this part of the state to this reducer function, whenever we call it; it doesn’t know it by itself.
This is the reducer file for the posts, from the Learn Redux repo:
function posts(state = [], action) {
switch (action.type) {
case 'INCREMENT_LIKES' :
const i = action.index;
return [
...state.slice(0, i),
{ ...state[i], likes: state[i].likes + 1 },
...state.slice(i + 1)
];
default:
return state;
}
}
You see the posts function, even though it says state; it is actually only managing the state.posts part of the state. The initial/default state is an empty array.
Now on to how the combineReducers function works you should read this part of the Redux documentation in and out, to have a proper mental model on how everything works; but here is the gist; when you do this:
// As all the reducers, and the corresponding parts of the state they handle...
// ...have the same names...
// ...we can use ES6's object short-hand notation, in the following way
combineReducers({
posts,
comments
});
…it is basically returning the complete state object after running the reducer functions on the corresponding parts of the state:
{
posts: posts(state.posts, action),
comments: comments(state.comments, action)
}
Hope this helps! Let me know if you have further questions. 😃