I am currently learning Redux, and I am confused on how the reducer know which action to take

For example,

const defaultState = {
  login: false
};

const reducer = (state = defaultState, action) => {
  // change code below this line
if(action.type === 'LOGIN') {
  return {
    login: true
  }
} else {
  return defaultState
}
  // change code above this line
};

const store = Redux.createStore(reducer);

const loginAction = () => {
  return {
    type: 'LOGIN'
  }
};

How does the reducer know to take the const loginAction as the action?

I’ll try to explain the whole system as simple as possible.

So you have redux state which holds some information. Usually it’s an object with some props. When you want to change some part of the state you dispatch an action which is an object containing type field and some data fields. In order to update the redux state you write reducers. Reducer receives dispatched action object and based on type field decides how to update the state.

1 Like

It all starts with action creator. Action creator is a function that returns an action which is simply an object. That object must have a property called type no matter what (you need to define type because that’s how you know what to send to reducers). Later, you dispatch that action just to make it communicate with all reducers . When you do that , it internally calls all reducers and compare its type with all the types inside them. At the end, state returns from the matched condition or default condition.

Action you see in every reducer function as an argument, is actually the same action you pass with dispatch.

1 Like