user3667098
user3667098

Reputation: 65

Redux: Why do we need actions?

I'm working with NgRx to implement Redux. I'm trying to understand the redux pattern. Why do we need to dispatch an action? Why can't we just call the userReducer function directly from the service code below passing the correct action? Thanks!

Service code:

this.store.dispatch(new userActions.SetName({"bob"})

user.action.ts:

    readonly type = UserActionTypes.SET_NAME
    constructor(public payload: string) { }
    }

user.reducer.ts:

export function userReducer(
   state: UserState = BEGINNING_STATE
   action: UserActions
)
switch(action.type) {
case UserActionTypes.SET_NAME:
   return {
      ...state,
      Name: state.Name
   }
}

Upvotes: 1

Views: 97

Answers (1)

HMR
HMR

Reputation: 39250

You seperate "indicate something happened" (action) from "do this if X happened" (reducer/middleware). If you call reducer directly then you don't have this separation so if you refactor a button that dispatched INCREMENT to a button that executes one specific reducer you just changed the code to having a button that when clicked indicates INCREMENT happened to having a button that when clicked changes the state in a particular way. There are many advantages that this separation can have in big complex applications.

Facebook had a large app where multiple people in multiple locations in the world worked on (facebook chat) and in this app there are multiple components that should indicate something happened but would instead directly change the state or caused side effects that broke other people's code. So they came up with a pattern that fixed this. Developers could now create components that would only indicate that something happened so other developers could write the code what needs to done when certain things happen.

The redux devtools save the actions and the resulting state so debugging can be made easier. If something doesn't work the first thing you should do is check the devtools to see if the correct actions are dispatched and they changed the state correctly.

Writing to state with actions and reducers is just one part, you should use selectors to read state in a composable and re usable way.

Upvotes: 1

Related Questions