Knowledge Transfer

Thursday, September 21, 2017

Building Redux in TypeScript with Angular 4 (Angular 2+)


 Building Redux in TypeScript with Angular 4 (Angular 2+)
For many Angular projects we can manage state in a fairly direct way: We tend to grab data from services and render them in components, passing values down the component tree along the way.
Managing our apps in this way works fine for smaller apps, but as our apps grow, having multiple components manage different parts of the state becomes cumbersome. For instance, passing all of our values down our component tree suffers from the following downsides:
Intermediate property passing – In order to get state to any component we have to pass the values down through inputs. This means we have many intermediate components passing state that it isn’t directly using or concerned about
Inflexible refactoring – Because we’re passing inputs down through the component tree, we’re introducing a coupling between parent and child components that often isn’t necessary. This makes it more difficult to put a child component somewhere else in the hierarchy because we have to change all of the new parents to pass the state
State tree and DOM tree don’t match – The “shape” of our state often doesn’t match the “shape” of our view/component hierarchy. By passing all data through the component tree via props we run into difficulties when we need to reference data in a far branch of the tree
State throughout our app – If we manage state via components, it’s difficult to get a snapshot of the total state of our app. This can make it hard to know which component “owns” a particular bit of data, and which components are concerned about changes
Pulling data out of our components and into services helps a lot. At least if services are the “owners” of our data, we have a better idea of where to put things. But this opens a new question: what are the best practices for “service-owned” data? Are there any patterns we can follow? In fact, there are.
In this post, we’re going to discuss a data-architecture pattern called Redux which was designed to help with these issues. We’ll implement our own version of Redux which will store all of our state in a single place. This idea of holding all of our application’s state in one place might sound a little crazy, but the results are surprisingly delightful.


Happy Coding,
Bhaskar

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]



<< Home