Forward to the Past or data fetching in React.js
React.js came with idea that JavaScript rendering logic and HTML markup should be together because this is a single logical piece of program and no need to switch between markup / JavaScript files. That was difficult to understand (oops 2000-x came back with single php file) but amazing as result.
Last few years we saw Flux, Redux and another *ux concepts for organizing React.js codebase. The next step was Relay with declarative data fetching. Relay does same as React did before — it brings another piece of our codebase to our React.js HTML & JavaScript file — data fetching.
Now we have HTML markup, JavaScript logic and data fetching in single file. This is awesome: there is no need to switch between files, there is no need to hang around and understand data flow — we know that exactly everything we need for current view file can be founds within this file.
Unfortunately Relay works only with GraphQL (which is also very cool) but concept it introduces can be reused even with no Relay itself.
SO…
Let’s follow same concept and bring next logical piece of our view — data into our view. Why? Because we can. Because i want to see and understand data flow, HTML markup and JavaScript logic within single file — smart component. Many years ago we wrote SQL queries mixed with markup in our PHP files.
Was it great? No. Did it work? Yes.
But we’ve learned a lot. I believe now we can go Forward to the Past and make it better.
Let’s start from simple steps — let’s remove Actions from Redux concept and move data flow in our container. This is not related to Redux itself and can be reused with any code organization.
Okay so what do we see? We did a small change which gave us visibility of our data fetching flow.
That looks okay for simple queries but what if we would need reuse some complex data fetching sequence? Well, here is idea of data layer or webutils comes. If we would need to reuse some complex data fetching which is mostly edge case, we are moving this piece of code to data layer.
This data layer can be used anywhere in the system and even combined with another data layers. I am using this concept in my projects and it works really well.
UI becomes more and more complex nowadays but I believe we can go Forward to the Past and make our life simpler.
Thanks for reading, any comments are welcome, stay in touch.
P.S. Here is a link to sample project to play with https://github.com/artyomtrityak/react-data-fetching