Polymer loves Redux
Web Components are an amazing way to componentized web applications in small, reusable pieces. Coding with Polymer, even reusability stops feeling like an afterthought but something one naturally does.
Decentralization rocks … but not everywhere
Yet — although UX components strongly gain from decentralization — other aspects of an application do require centralization. Take for example a todo application: Marking a todo as done on the todo’s detail page should add a check mark on the todos lister page and decrease the counter of open todos.
Polymer’s data binding can handle such simple situations but it will quickly turn into a mess once the application becomes a bit more complex: all parts of the application can mutate data, thereby triggering other updates, which in turn trigger again mutations.
At the same time in another world
Surprise, surprise, this problem is of course not Polymer specific. In fact, the React community faced exactly the same challenge and solved it with the Flux pattern, which prescribes an unidirectional data flow to reduce the overall system complexity. Best of all, Flux isn’t a (React-specific) framework but just a pattern, which is implemented by many libraries.
Lately, one specific Flux implementation took over: Redux — which reduces complexity even further by limiting to pure functions that generate new versions of the read-only application state. Although Redux is a library — it’s again independent of React (although mainly used there). Aside being battle proven, Redux gained a large developer community and comes with tons of amazing learning materials.
So, instead of reinventing the wheel: How about letting Redux handle the state of our Polymer applications?
Marrying Polymer and Redux
Christopher Turner wrote polymer-redux, a Polymer binding that makes using Redux easy as cake (check its Github page for an excellent getting started guide).
In a nutshell, polymer-redux makes the state of the Redux store accessible via Polymer properties. For example, to bind the property todos to the path todos.all in the Redux Store:
var ReduxBehavior = PolymerRedux(MyReduxStore);
Any element with the PolymerRedux behavior can as well dispatch actions to the Redux Store to trigger the reducers:
And that’s all the gluing there is! Everything else is pure Polymer and pure Redux. Really sweet.
Want to learn more about Polymer? Have a look to all our Medium posts on Polymer.