DEV Community

sarisgar28
sarisgar28

Posted on

Continuing with React and Redux… I want to talk about REDUCERS!

Reducers are functions that take the current STATE and ACTION as arguments returning a NEW STATE.

const expenseReducer = (state = [], action) => {
   switch (action.type){
       case "SET_EXPENSE":
       return action.payload.expense || state
       case "ADD_EXPENSE":
           return [...state,action.payload]
        case "REMOVE_EXPENSE":
           return state.filter(expense => expense !== 
 action.payload)
       default:
       return state

   }   
 };
Enter fullscreen mode Exit fullscreen mode

(Make sure to pass the initial state with the right data structure)

An important thing about reducers is they are pure functions meaning:
Pure functions are only determined by their input values.
Pure functions have no side effects, meaning they don’t have any effect outside the function, it will only return a value.

For separations of concerns you normally do one reducer by component, so if we have more than one (you most likely will) we can use something call “combineReducers()” method and it will go on a separate folder such as index.js

frontend/src/redux/reducer/index.js


import userReducer from './userReducer'
import expenseReducer from './expenseReducer'




export default combineReducers({
   user: userReducer,
   expenses: expenseReducer


})
Enter fullscreen mode Exit fullscreen mode

The structure for redux is to split the state into multiple slices or domains by key and provide a separate reducer to manage each individual slice of data as the redux docs say, combineReducers method is not required but it is useful to put all your data together.

The combineReducers helper function turns an object whose values are different reducing functions into a single reducing function you can pass to createStore. Passing the state as objects gives them a key and a value, you can control state key names by using different keys in the passed value.

You can read more about it here:
https://redux.js.org/api/combinereducers

HAPPY CODING! :)

Top comments (1)

Collapse
 
rubenarushanyan profile image
Ruben Arushanyan