Latest news about Bitcoin and all cryptocurrencies. Your daily crypto news habit.
Apollo vs Redux — rendering with data
Apollo and Redux are 2 popular libraries used with React. They are included for various reasons, but mainly for:1. Managing a store 2. Assistance handling data fetching 3. Triggering any re-rendering with updated props
But what mechanisms do they use under-the-hood to do this, and how do they differ when it comes to handling props and rendering?
I decided to investigate and below is the product of that.
TLDR;
Apollo uses an Observable and manually forces a re-render, reading the current Observable for data at render-point.
Redux uses an Observable too, but updates local state for its subscribers using observer notifications.
Observables
Something important to touch on first are Observables. They are a new async primitive with some powerful properties. A basic example is below.
- Create your Observable from a subscription function
const subscriptionFunction = (observer) => { // do some stuff, could be async. observer.next("Call with some data"); observer.complete(); return () => console.log("Unsubscribing")}const ourObservable = new Observable(subscriptionFunction);
2. Subscribe to your Observable. This will invoke the subscriptionFunction.
const subscriber = ourObservable.subscribe({ next(x) { console.log(x) }, // “Call with some data" error(err) { console.log("Received terminating error of the sequence.") }, complete() { console.log("Stream has completed successfully.") }});subscriber.unsubscribe(); // "Unsubscribing"
Basically we can define a 1-to-many relationship between objects. When the state changes for the parent observable, its dependents (the observers) are notified and updated.
They have several powerful properties including being lazy, cancelable and can run multiple times in a sequence.
Check out zen-observable to make use of them in a spec-compliant way today.
Let’s start with Apollo
Apollo makes use of fetch inside an Observables subscription function (find full details on Apollo’s internals in a recent talk I did here). The Observable also serves as a Store for normalised data.
On receiving the response from a HTTP request the Store is updated and then a “forceRender()” is triggered (Reacts method to manually trigger a re-render inside a given component).
Lastly using the “render prop pattern”, children are rendered with data off the current Observable. Worth noting that React state has not been used at all here.
See below for a breakdown of events on a page-load with a basic Query component.
Full anatomy of a page-load with Apollo
Now onto Redux
With Redux we will ignore the actual HTTP fetching mechanism (assuming either thunks or sagas are used for this) and focus on store updates and component re-renders.
When a component “connects()” it is added to the list of subscribers for the Store Observable (more on the Redux Store Observable here).When a reducer changes state in the Store, all the subscribers are notified and run a “setState()”.
The result is the connected component and its children are re-rendered with updated props.
A simplified version of Redux’s connect is below:
class Connect extends Component { trySubscribe() { this.unsubscribe = this.store.subscribe(this.handleChange.bind(this)) this.handleChange() }
componentDidMount() { this.trySubscribe() }
handleChange() { const storeState = this.store.getState() const prevStoreState = this.state.storeState // logic using store and react state // if the Store state has changed, update Reacts state this.setState({ storeState }) }}
Summary
I find it fascinating that both libraries make use of Observables even though they use it with different mechanisms.
I think if nothing else it shows the kind of role which Observables will have in the future of Javascript. They are in Stage 1 of the official proposal currently (full details at tc39 here), so hopefully landing soon. Considering the kind of power they bring to the table (solving problems which Promises are Streams sometimes can’t) it seems there is a good number of scenarios which will be well suited for them.
Reading working examples of them in the wild, like that in Redux and Apollo, is a great way to learn more about them.
Next I would like to examine the pros and cons of these approaches and try to reason why these libraries chose the approach they did.
If you liked this please spare a clap. Alternatively let me know if you have any thoughts or feedback. Thanks :)
Apollo vs Redux — rendering with data was originally published in HackerNoon.com on Medium, where people are continuing the conversation by highlighting and responding to this story.
Disclaimer
The views and opinions expressed in this article are solely those of the authors and do not reflect the views of Bitcoin Insider. Every investment and trading move involves risk - this is especially true for cryptocurrencies given their volatility. We strongly advise our readers to conduct their own research when making a decision.