Professional Documents
Culture Documents
Your NGRX Cheat Sheat
Your NGRX Cheat Sheat
Your NGRX Cheat Sheat
CHEAT SHEET
CONF
CONF
CONF
DATA FLOW
One of the most important parts of NGRX is understanding the data flow. Once
you understand this it’s easy to follow any state conversation you might be
involved in. One of the best ways to understand the flow is with a diagram.
This diagram from ngrx.io is one of the best around.
The dark boxes (component and service) represent code that isn’t part of the
state. Components use the state by subscribing to the Selectors and interact
with state by dispatching actions. Services will be used by Effects in order to
interact with a data store. The rest of the boxes represent concepts in NGRX.
Let’s look at the flow starting with the component. A component will dispatch
an action. Reducers watch for dispatched actions and will change data in the
store. Selectors watch for changes to the data in the store and emit the new
values from the store for the component to use.Effects can also trigger from an
Action and are in a sense separate from the state flow. When an effect is
triggered it will run it’s code (often interacting with a data store) and dispatch
a new Action which will continue through the normal flow all the way back to
the component.
ng-conf.org CONF
ACTION - HOW WE INTERACT WITH THE STATE
Actions are how you trigger changes to state. When you dispatch an action both
effects and reducers listen for it. Actions should be descriptive and used for a
specific purpose. They drive the redux dev tools and yelp you understand the
flow of data in your application.
State is immutable which means that you can’t modify the state. You have to
replace it. A Reducer file will define the shape of the state it manages and holds
the Reducer function which handles changing the state. The Reducer function
takes an Action and the current state then returns an object matching the state’s
type. In the case that no change was needed the function returns the same state
that was passed into it. Otherwise, it will return a new state containing any
changes triggered by the Action that was passed in.
ng-conf.org CONF
SELECTORS - HOW WE GET DATA FROM STATE
An analogy would be that state is a database and Selectors are the queries. They
can be as simple as getting a single property from the state. They can also be
very complex combining data from multiple Selectors and generating
computed values.
You can think of them as the side Effects of an Action being triggered. For
instance if you have an Action for “Get User” a side effect of that Action
would be fetching the user data from the database. The fetch code should be
in an Effect. Having Effects helps separate concerns like backend
interactions from the flow of data through state. Once the data is retrieved
the effect will dispatch the Action “Get User Success” which will get picked
up by the Reducer.