Make Use of RxJS to Create Efficient React Components With Ease
We’ll discuss a pattern to implement efficient React components using the RxJS framework
React components are based on the concept of properties and states. While properties represent the input values from other (host) components, the state represents the internal condition of a component. The state can be derived from properties or even be computed asynchronously — e.g.. as a result of making HTTP calls.
The React library makes sure to rerender a component when updates to properties or the state will have a visual effect.
From a performance perspective, we want make sure:
- The execution of the
rendermethod of a component should be as fast as possible — i.e., we want to avoid doing expensive computations or object allocations
- The number of times the
rendermethod is invoked should be as small as possible. Each time
renderis called, React has to run its reconciliation algorithm to compare the virtual DOMs of the update vs the existing state. Although this is implemented very efficiently, it’s even more efficient to avoid reconciliation altogether.
Minimizing Render Time
We minimize the time spent in the
render method by precomputing all required data structures beforehand. This includes potentially expensive computations as well as object allocations.
We use RxJS operators to react to changes of the input and use the
state concept to carry the result of our computations and object creations over to the
It’s the responsibility of the component developer to tell if a modification of a property or state results in a rerendering of the application. This is typically done by overriding the
shouldComponentUpdate method or by deriving from
PureComponent for simple use cases.
Per default, React will rerender a component if a property or the state changes. Deriving from
PureComponentimproves this situation a bit by doing a shallow comparison of the properties, assuming immutability of the objects themselves. Still this approach can lead to undesired rerender operations because:
- The rendering of the component might not depend directly on a property but rather on derived information of that property. And that might stay stable despite the property changing.
- For controlled components, we often pass in callback functions via properties. We can sometimes observe the (anti)pattern that host components bind member functions to callbacks inside their
rendercalls or that they use Lambda functions generated during render. This will create new function objects each time the host renders, causing an unnecessary rerender of the child component.
So in order to avoid these issues, our strategy is to make sure the rendering of the component does NOT use properties directly — but only information from the
This is information the component developer has full control over. We also mandate objects carried in the component
state are immutable so we can tell by a simple equals check if the state changed or not.
Separation of Concerns
The discussed optimization patterns pivot around the idea of computing the ideal
state for the rendering of a component.
This gives us the opportunity to separate the task for computing this state into a Business Logic Component (BLoC) and the actual rendering into a presentation component.
Before we start to explain the approach, let’s add a very simple “Hello, World!” example.
We’ll use the rx-react-component implementation of the discussed pattern:
- Constructing a component with
HelloWorldPropsas input. The component will implement some simple business logic (prefix the input with
'Hello') and then pass the result to a presentation component.
- The business-logic layer that transforms the input properties to state. Note how the distinctUntilChanged operator makes sure to update the state only if the input has really changed.
- The presentation component realized as a function component.
We implement an anonymous class for our performance optimized reactive component. The purpose of this class is to:
- Expose a reactive RxJS way to compute the
statefrom properties, including reactive access to life-cycle methods
- Minimize reconciliation by implementing the
Minimizing Render Time
The abstract class takes a function to convert the properties into a state Observable. It’ll then make sure to correctly hook into the life-cycle methods to subscribe and unsubscribe.
The caller constructs the
state$ Observable based on input properties (via the
props$ Observable) or by using RxJS mechanisms to compute state asynchronously.
Any state that is emitted by the
state$ Observable before the
componentDidMount method is invoked is considered an initialization state automatically. You might use the startWith operator to make sure such a state exists. There’s no need (and no way) to set
Input from the host component
Our React component will receive its input via properties from its host. These properties are made available via the
Input from child components
Communication from a child component to the parent component typically works by passing a callback function as an event handler via a property into the child.
We distinguish between controlled or uncontrolled components. A controlled component delegates its state to its host component and expects state changes to be mirrored back via its properties. An uncontrolled component maintains its own state.
Since we split our component into a BLoC and a presentation component, the presentation component should always be controlled by the BLoC, whereas the BLoC can be controlled or uncontrolled.
Controlling the presentation component: We define callback functions for the view component’s state changes and manage them in the state of the BLoC. These functions are bound
next calls on a Subject which allow the BLoC to integrate these callbacks into the observable pipe.
Uncontrolled BLoC: The uncontrolled BLoC typically maintains its state via a scan operator.
Example: Imagine a component that maintains a counter value. The view component displays the value and renders a button to increment it.
Controlled BLoC: The controlled BLoC delegates state management to its host via a callback function in its properties.
Example: Again, we have a counter with a button to increment it. This example uses the identical-view implementation compared to the previous sample.
The abstract class implements
shouldComponentUpdate and compares the new state against the current state using a simple
equals check. Properties are ignored completely. This works, because
- Objects are immutable
- All information derived from properties should be converted to
Separation of Concerns
We use the
rxComponent function to create our component. This function accepts a function to compute the
state$ observable from the properties, life-cycle Observables, and a reference to a presentation component that accepts the state as its input properties.
This approach has the following advantages:
- Clearly separates business logic from rendering logic
- No need to create a custom class per component, thus reducing the overall application size