How ACTION data is send to REDUCER in redux

Viewed 311

I have made an counter app and using redux for state management, and working fine but i am confuse that how reducer function is getting the action data even we have not imported action function in reducer file.

Using following Architecture:

enter image description here enter image description here

Here is ACTION file code:

export const inc = () => {
   return{
       type: "INCREMENT"
   }
}

export const dec = () => {
    return{
        type: "DECREMENT"
    }
 }

and Here is reducer file code:

const InitialState = 0;

const changeNumber = (state = InitialState, action) => {
    switch (action.type){
        case "INCREMENT": return state + 1;
        case "DECREMENT": return state - 1;
        default: return state;
    }
}

export default changeNumber;

Reducer file function have to two parameters state and action. Where current state value is 0 and action value is an object which is coming from action file but how?

and as you know also having store white hold the global state and using redux official document for this.

1 Answers

When you call store.dispatch(myAction), store then goes to call the reducer with reducer(lastState, myAction), takes the result of that and makes that result the new state.

If you have used configureStore or combineReducers to combine multiple reducers into one, every action is sent to every reducer in there.

Generally: as you are talking about an "actions file" and using string types I want to make you aware that you are probably learning a very outdated style of Redux. Modern Redux does not use switch..case reducers, ACTION_TYPES, immutable reducer logic, createStore or connect and is only 25% of the code you are writing right now. To learn modern Redux, please follow the official Redux Essentials Tutorial.

Even if you want to learn old-style Redux, you are probably still following outdated documentation since we do not really recommend "actions files" or "action folders" any more. In case you want to learn old-style Redux, I would recommend you to follow the official Redux Fundamentals Tutorial. But per default, go for modern Redux. It is the official recommendations since 2019.

Related