How to Make Use of RxJS to Create Efficient React Components with Ease

How to Make Use of RxJS to Create Efficient React Components with Ease

React components are based on the concept of properties and states. ... Make Use of RxJS to Create Efficient React Components With Ease.

Introduction

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 render method 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 render method is invoked should be as small as possible. Each time render is 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 render method.

Avoiding Reconciliation

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 render calls 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 state.

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.

Example

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:

import * as React from 'react';
import { pipe } from 'rxjs';
import { map, pluck, distinctUntilChanged } from 'rxjs/operators';

import { rxComponent } from 'rx-react-component';

export interface HelloWorldProps {
  name: string;
}

export interface HelloWorldState {
  text: string;
}

// 1
export const HelloWorld = rxComponent<HelloWorldProps, HelloWorldState>(
  // 2
  pipe(
    pluck('name'),
    distinctUntilChanged(),
    map(name => ({ text: `Hello ${name}` }))
  ),
  // 3
  ({ text }) => <div>{text}</div>
);

“Hello, World!” example

Explanation:

  1. Constructing a component with HelloWorldProps as input. The component will implement some simple business logic (prefix the input with 'Hello') and then pass the result to a presentation component.
  2. 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.
  3. The presentation component realized as a function component.

Approach

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 state from properties, including reactive access to life-cycle methods
  • Minimize reconciliation by implementing the shouldComponentUpdate method

Component design with the RxJS business layer in the BLoC and the separation of the view layer into a dumb presentation component

Minimizing Render Time

We represent the React life-cycle methods as Observables and derive the component state using reactive operators.

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.

Initial state

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 this.state explicitly.

Input from the host component

Our React component will receive its input via properties from its host. These properties are made available via the props$ Observable.

Use operators such as pluck and distinctUntilChanged to access individual properties, and change the state only if these properties change.

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.

Layout of an uncontrolled component. The BLoC maintains its state via a scan operator and updates it when triggered by a click subject.

Example: Imagine a component that maintains a counter value. The view component displays the value and renders a button to increment it.

/**
 * Properties of the final component
 */
export interface CounterProps {
  // some initial counter value
  initial: number;
}
/**
 * Properties of the view-only component
 */
export interface CounterViewProps {
  // the current counter value
  counter: number;
  // callback that allows to increment the counter
  onClick: UnaryFunction<MouseEvent, void>;
}
/**
 * The view only component
 */
const viewOnly = ({ counter, onClick }: CounterViewProps) => (
  <div>
    <div>Counter {counter}</div>
    <button onClick={onClick}>Increment</button>
  </div>
);
/**
 * The business logic component
 */
function bloc(props$: Observable<CounterProps>): Observable<CounterViewProps> {
  // extract the initial value from the props
  const initial$ = props$.pipe(prop('initial'));
  // subject to react to button clicks
  const clickSubject = new Subject<any>();
  const click$ = initial$.pipe(
    /* here we maintain the component state, each time the 
     * button is clicked, the subject fires and the counter
     * is incremented */
    switchMap(initial => clickSubject.pipe(scan(value => value + 1, initial)))
  );
  // for convenience we bind the next function
  const onClick = bindNext(clickSubject);
  const value$ = merge(initial$, click$);
  // map the counter value to the input props of the view component
  return value$.pipe(map(counter => ({ counter, onClick })));
}
export const Counter = rxComponent<CounterProps, CounterViewProps>(
  bloc,
  viewOnly
);

Example of an uncontrolled counter component

Controlled BLoC: The controlled BLoC delegates state management to its host via a callback function in its properties.

Layout of a controlled component. The reactive layer transforms the input properties to the state and dispatches clicks back to the controller.

Example: Again, we have a counter with a button to increment it. This example uses the identical-view implementation compared to the previous sample.

/**
 * Properties of the final component
 */
export interface ControlledCounterProps {
  // counter, maintained by the host component
  value: number;
  // callback to send a new value
  onValue: UnaryFunction<number, void>;
}

/**
 * The business logic component
 */
function bloc(
  props$: Observable<ControlledCounterProps>
): Observable<CounterViewProps> {
  // the controlled input
  const value$ = props$.pipe(prop('value'));

  // subject to react to button clicks
  const clickSubject = new Subject<any>();
  const onClick = bindNext(clickSubject);

  const click$ = clickSubject.pipe(
    /* A click will update the current value
     * and will use the current callback function */
    withLatestFrom(value$, props$),    
    map(([, value, { onValue }]) => onValue(value + 1)),
    // this keeps the sequence live but does not emit anything
    switchMapTo(EMPTY)
  );

  /**
   * We merge the clicks with the values to keep the pipe
   * alive. Since click$ will never emit anything, this
   * does not mess up our state.
   */
  return merge(value$, click$).pipe(map(counter => ({ counter, onClick })));
}

export const ControlledCounter = rxComponent<
  ControlledCounterProps,
  CounterViewProps
>(bloc, viewOnly);

Example of a controlled counter component

Avoiding Reconciliation

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 state via the state$ observable

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

Summary

  • Split your component into a Business Logic Component (BLoC) and a presentation component
  • Implement the BLoC using RxJS to transform properties and context into state
  • Use built-in RxJS operators for initialization (startWith), to minimize updates (distinctUntilChanged), to maintain state (scan), and to combine with contextual, potentially asynchronous data (merge, switch, etc.).
  • Pass the resulting state as input properties to the presentation component

Resources

Thank for reading! I hope this tutorial will surely help and you if you liked this tutorial, please consider sharing it with others.

JavaScript Rxjs React Programming Webdev

Bootstrap 5 Complete Course with Examples

Bootstrap 5 Tutorial - Bootstrap 5 Crash Course for Beginners

Nest.JS Tutorial for Beginners

Hello Vue 3: A First Look at Vue 3 and the Composition API

Building a simple Applications with Vue 3

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

How native is React Native? | React Native vs Native App Development

Article covers: How native is react native?, React Native vs (Ionic, Cordova), Similarities and difference between React Native and Native App Development.

How to use Functional Programming in your React app | React Next

In the past few years, the buzz around functional programming has been growing, but it can be challenging to apply theoretical concepts to everyday work. How can we make the code we work on more functional? What advanced patterns can you use, and why should you do that? And what do React hooks have to do with all this? In this talk we’ll have a look at real-life examples and patterns you can use to make React apps more functional.

JavaScript Date: Building a React Hook For Date Selector

This week, I had to construct a date selector form in React that looks like this. As you can see, the user interface includes the surrounding month and date options in addition to the selected date. This means that I need to not only keep track of the current date, but I also need a way to conveniently figure out how many days are in the selected month.

Forms of Composition in JavaScript and React

One of the core ideas in functional programming is composition: building larger things from smaller things. The canonical example of this idea should be familiar with legos.

Functional Programming in JavaScript

Let’s talk about the raw way of writing functions. Functions perform certain set of actions according to our requirements which could include fetching data, updating State, changing a set of mutable values and updating the DOM and so on.