Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why all redux reducer functions execute at runtime?

I'm trying to get deep knowledge with React + Redux + thunk

Consider it, it this case I'm using react-redux and redux-thunk !

For example I've 2 reducer in my App :

function loadingReducer(state = false, action) {
    console.log('loadingReducer');
    
    switch(action.type) {
        case 'LOADING':
            return action.loading
        default:
            return state
    }
}

function itemsReducer(state = [], action) {
    console.log('itemsReducer');
    
    switch(action.type) {
        case 'ITEMS':
            return action.data
        default:
            return state
    }
}

At run time all functions executes and I've 4 console.log in browser console for each reducer and finally six console.log, this means the redux executed and checked six times thoes reducer functions and I think it's not optimized performance for a large scale project ...

So, the major question, Is here a trick to handle this issue or I should use other packages like saga or mobx to handle it ?

thanks

like image 884
Alex Avatar asked Mar 30 '26 22:03

Alex


2 Answers

The reason for all of the console logs running is because of how combineReducers works...which is to essentially go through every reducer's code. But most of it is not executed since it resides inside a switch statement. So this doesn't create performance issues.

If you're talking about the multiple logs at the start of the application..that is because redux dispatches 2-3 actions at the start of the application (which, as stated above, will cause all logs to run. You can check them by logging the action itself in one of these reducers with console.log(action).

In general, if you do not have a lot of code outside the switch statements in your reducers then you'll be fine. Which works out anyway, since with redux-thunk most of your code should go in your actions while reducers just change the state.

like image 85
ManavM Avatar answered Apr 02 '26 12:04

ManavM


All reducers are called each time an action is dispatched i.e application state is changed.

Any reducer can chose to listen for any action and update its state if it wants. When reducers are attached to a store, they are responsible for handling a part of the application.

A usecase for this would be: When you have a cart reducer, a shopping page reducer and a shopping page.

The shopping page dispatches an action saying that an item was added to cart. The reducer for shopping page listens to this and updates the items status indicating with green that it has been added to cart

The cart reducer which is responsible for the cart icon also receives this message and updates the count.

like image 39
SoWhat Avatar answered Apr 02 '26 11:04

SoWhat



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!