Skip to content Skip to sidebar Skip to footer

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

Solution 1:

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.


Post a Comment for "Redux: Why Do We Need Actions?"