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:
render
method of a component should be as fast as possible — i.e., we want to avoid doing expensive computations or object allocationsrender
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.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.
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 PureComponent
improves 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:
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.
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:
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:
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.We implement an anonymous class for our performance optimized reactive component. The purpose of this class is to:
state
from properties, including reactive access to life-cycle methodsshouldComponentUpdate
methodComponent design with the RxJS business layer in the BLoC and the separation of the view layer into a dumb presentation component
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.
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.
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.
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
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
state
via the state$
observableWe 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:
startWith
), to minimize updates (distinctUntilChanged
), to maintain state (scan
), and to combine with contextual, potentially asynchronous data (merge
, switch
, etc.).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