Welcome to Knowledge Base!

KB at your finger tips

This is one stop global knowledge base where you can learn about all the products, solutions and support features.

Categories
All

Web-React

Forwarding Refs – React

Forwarding Refs

Ref forwarding is a technique for automatically passing a ref through a component to one of its children. This is typically not necessary for most components in the application. However, it can be useful for some kinds of components, especially in reusable component libraries. The most common scenarios are described below.


Forwarding refs to DOM components


Consider a FancyButton component that renders the native button DOM element:


function FancyButton(props) {
return (
<button className="FancyButton">
{props.children}
</button>
);
}


React components hide their implementation details, including their rendered output. Other components using FancyButton usually will not need to obtain a ref to the inner button DOM element. This is good because it prevents components from relying on each other’s DOM structure too much.


Although such encapsulation is desirable for application-level components like FeedStory or Comment , it can be inconvenient for highly reusable “leaf” components like FancyButton or MyTextInput . These components tend to be used throughout the application in a similar manner as a regular DOM button and input , and accessing their DOM nodes may be unavoidable for managing focus, selection, or animations.


Ref forwarding is an opt-in feature that lets some components take a ref they receive, and pass it further down (in other words, “forward” it) to a child.


In the example below, FancyButton uses React.forwardRef to obtain the ref passed to it, and then forward it to the DOM button that it renders:



const FancyButton = React.forwardRef((props, ref) => (  <button ref={ref} className="FancyButton">    {props.children}
</button>
));

// You can now get a ref directly to the DOM button:
const ref = React.createRef();
<FancyButton ref={ref}>Click me!</FancyButton>;


This way, components using FancyButton can get a ref to the underlying button DOM node and access it if necessary—just like if they used a DOM button directly.


Here is a step-by-step explanation of what happens in the above example:



  1. We create a React ref by calling React.createRef and assign it to a ref variable.

  2. We pass our ref down to <FancyButton ref={ref}> by specifying it as a JSX attribute.

  3. React passes the ref to the (props, ref) => ... function inside forwardRef as a second argument.

  4. We forward this ref argument down to <button ref={ref}> by specifying it as a JSX attribute.

  5. When the ref is attached, ref.current will point to the <button> DOM node.



Note


The second ref argument only exists when you define a component with React.forwardRef call. Regular function or class components don’t receive the ref argument, and ref is not available in props either.


Ref forwarding is not limited to DOM components. You can forward refs to class component instances, too.



Note for component library maintainers


When you start using forwardRef in a component library, you should treat it as a breaking change and release a new major version of your library. This is because your library likely has an observably different behavior (such as what refs get assigned to, and what types are exported), and this can break apps and other libraries that depend on the old behavior.


Conditionally applying React.forwardRef when it exists is also not recommended for the same reasons: it changes how your library behaves and can break your users’ apps when they upgrade React itself.


Forwarding refs in higher-order components


This technique can also be particularly useful with higher-order components (also known as HOCs). Let’s start with an example HOC that logs component props to the console:


function logProps(WrappedComponent) {  class LogProps extends React.Component {
componentDidUpdate(prevProps) {
console.log('old props:', prevProps);
console.log('new props:', this.props);
}

render() {
return <WrappedComponent {...this.props} />; }
}

return LogProps;
}


The “logProps” HOC passes all props through to the component it wraps, so the rendered output will be the same. For example, we can use this HOC to log all props that get passed to our “fancy button” component:


class FancyButton extends React.Component {
focus() {
// ...
}

// ...
}

// Rather than exporting FancyButton, we export LogProps.
// It will render a FancyButton though.
export default logProps(FancyButton);


There is one caveat to the above example: refs will not get passed through. That’s because ref is not a prop. Like key , it’s handled differently by React. If you add a ref to a HOC, the ref will refer to the outermost container component, not the wrapped component.


This means that refs intended for our FancyButton component will actually be attached to the LogProps component:


import FancyButton from './FancyButton';

const ref = React.createRef();
// The FancyButton component we imported is the LogProps HOC.
// Even though the rendered output will be the same,
// Our ref will point to LogProps instead of the inner FancyButton component!
// This means we can't call e.g. ref.current.focus()
<FancyButton
label="Click Me"
handleClick={handleClick}
ref={ref}/>
;


Fortunately, we can explicitly forward refs to the inner FancyButton component using the React.forwardRef API. React.forwardRef accepts a render function that receives props and ref parameters and returns a React node. For example:


function logProps(Component) {
class LogProps extends React.Component {
componentDidUpdate(prevProps) {
console.log('old props:', prevProps);
console.log('new props:', this.props);
}

render() {
const {forwardedRef, ...rest} = this.props;
// Assign the custom prop "forwardedRef" as a ref
return <Component ref={forwardedRef} {...rest} />; }
}

// Note the second param "ref" provided by React.forwardRef.
// We can pass it along to LogProps as a regular prop, e.g. "forwardedRef"
// And it can then be attached to the Component.
return React.forwardRef((props, ref) => { return <LogProps {...props} forwardedRef={ref} />; });}


Displaying a custom name in DevTools


React.forwardRef accepts a render function. React DevTools uses this function to determine what to display for the ref forwarding component.


For example, the following component will appear as ” ForwardRef ” in the DevTools:



const WrappedComponent = React.forwardRef((props, ref) => {
return <LogProps {...props} forwardedRef={ref} />;
});


If you name the render function, DevTools will also include its name (e.g. ” ForwardRef(myFunction) ”):



const WrappedComponent = React.forwardRef(
function myFunction(props, ref) {
return <LogProps {...props} forwardedRef={ref} />;
}
);


You can even set the function’s displayName property to include the component you’re wrapping:



function logProps(Component) {
class LogProps extends React.Component {
// ...
}

function forwardRef(props, ref) {
return <LogProps {...props} forwardedRef={ref} />;
}

// Give this component a more helpful display name in DevTools.
// e.g. "ForwardRef(logProps(MyComponent))"
const name = Component.displayName || Component.name; forwardRef.displayName = `logProps(${name})`;
return React.forwardRef(forwardRef);
}

Is this page useful? Edit this page

Fragments – React

Fragments

A common pattern in React is for a component to return multiple elements. Fragments let you group a list of children without adding extra nodes to the DOM.


render() {
return (
<React.Fragment>
<ChildA />
<ChildB />
<ChildC />
</React.Fragment>
);
}

There is also a new short syntax for declaring them.


Motivation


A common pattern is for a component to return a list of children. Take this example React snippet:


class Table extends React.Component {
render() {
return (
<table>
<tr>
<Columns />
</tr>
</table>
);
}
}

<Columns /> would need to return multiple <td> elements in order for the rendered HTML to be valid. If a parent div was used inside the render() of <Columns /> , then the resulting HTML will be invalid.


class Columns extends React.Component {
render() {
return (
<div>
<td>Hello</td>
<td>World</td>
</div>
);
}
}

results in a <Table /> output of:


<table>
<tr>
<div>
<td>Hello</td>
<td>World</td>
</div>
</tr>
</table>

Fragments solve this problem.


Usage


class Columns extends React.Component {
render() {
return (
<React.Fragment> <td>Hello</td>
<td>World</td>
</React.Fragment> );
}
}

which results in a correct <Table /> output of:


<table>
<tr>
<td>Hello</td>
<td>World</td>
</tr>
</table>

Short Syntax


There is a new, shorter syntax you can use for declaring fragments. It looks like empty tags:


class Columns extends React.Component {
render() {
return (
<> <td>Hello</td>
<td>World</td>
</> );
}
}

You can use <></> the same way you’d use any other element except that it doesn’t support keys or attributes.


Keyed Fragments


Fragments declared with the explicit <React.Fragment> syntax may have keys. A use case for this is mapping a collection to an array of fragments — for example, to create a description list:


function Glossary(props) {
return (
<dl>
{props.items.map(item => (
// Without the `key`, React will fire a key warning
<React.Fragment key={item.id}>
<dt>{item.term}</dt>
<dd>{item.description}</dd>
</React.Fragment>
))}
</dl>
);
}

key is the only attribute that can be passed to Fragment . In the future, we may add support for additional attributes, such as event handlers.


Live Demo


You can try out the new JSX fragment syntax with this CodePen.

Is this page useful? Edit this page
Read article

Higher-Order Components – React

Higher-Order Components

A higher-order component (HOC) is an advanced technique in React for reusing component logic. HOCs are not part of the React API, per se. They are a pattern that emerges from React’s compositional nature.


Concretely, a higher-order component is a function that takes a component and returns a new component.


const EnhancedComponent = higherOrderComponent(WrappedComponent);

Whereas a component transforms props into UI, a higher-order component transforms a component into another component.


HOCs are common in third-party React libraries, such as Redux’s connect and Relay’s createFragmentContainer .


In this document, we’ll discuss why higher-order components are useful, and how to write your own.


Use HOCs For Cross-Cutting Concerns



Note


We previously recommended mixins as a way to handle cross-cutting concerns. We’ve since realized that mixins create more trouble than they are worth. Read more about why we’ve moved away from mixins and how you can transition your existing components.



Components are the primary unit of code reuse in React. However, you’ll find that some patterns aren’t a straightforward fit for traditional components.


For example, say you have a CommentList component that subscribes to an external data source to render a list of comments:


class CommentList extends React.Component {
constructor(props) {
super(props);
this.handleChange = this.handleChange.bind(this);
this.state = {
// "DataSource" is some global data source
comments: DataSource.getComments()
};
}

componentDidMount() {
// Subscribe to changes
DataSource.addChangeListener(this.handleChange);
}

componentWillUnmount() {
// Clean up listener
DataSource.removeChangeListener(this.handleChange);
}

handleChange() {
// Update component state whenever the data source changes
this.setState({
comments: DataSource.getComments()
});
}

render() {
return (
<div>
{this.state.comments.map((comment) => (
<Comment comment={comment} key={comment.id} />
))}
</div>
);
}
}

Later, you write a component for subscribing to a single blog post, which follows a similar pattern:


class BlogPost extends React.Component {
constructor(props) {
super(props);
this.handleChange = this.handleChange.bind(this);
this.state = {
blogPost: DataSource.getBlogPost(props.id)
};
}

componentDidMount() {
DataSource.addChangeListener(this.handleChange);
}

componentWillUnmount() {
DataSource.removeChangeListener(this.handleChange);
}

handleChange() {
this.setState({
blogPost: DataSource.getBlogPost(this.props.id)
});
}

render() {
return <TextBlock text={this.state.blogPost} />;
}
}

CommentList and BlogPost aren’t identical — they call different methods on DataSource , and they render different output. But much of their implementation is the same:



  • On mount, add a change listener to DataSource .

  • Inside the listener, call setState whenever the data source changes.

  • On unmount, remove the change listener.


You can imagine that in a large app, this same pattern of subscribing to DataSource and calling setState will occur over and over again. We want an abstraction that allows us to define this logic in a single place and share it across many components. This is where higher-order components excel.


We can write a function that creates components, like CommentList and BlogPost , that subscribe to DataSource . The function will accept as one of its arguments a child component that receives the subscribed data as a prop. Let’s call the function withSubscription :


const CommentListWithSubscription = withSubscription(
CommentList,
(DataSource) => DataSource.getComments()
);

const BlogPostWithSubscription = withSubscription(
BlogPost,
(DataSource, props) => DataSource.getBlogPost(props.id)
);

The first parameter is the wrapped component. The second parameter retrieves the data we’re interested in, given a DataSource and the current props.


When CommentListWithSubscription and BlogPostWithSubscription are rendered, CommentList and BlogPost will be passed a data prop with the most current data retrieved from DataSource :


// This function takes a component...
function withSubscription(WrappedComponent, selectData) {
// ...and returns another component...
return class extends React.Component {
constructor(props) {
super(props);
this.handleChange = this.handleChange.bind(this);
this.state = {
data: selectData(DataSource, props)
};
}

componentDidMount() {
// ... that takes care of the subscription...
DataSource.addChangeListener(this.handleChange);
}

componentWillUnmount() {
DataSource.removeChangeListener(this.handleChange);
}

handleChange() {
this.setState({
data: selectData(DataSource, this.props)
});
}

render() {
// ... and renders the wrapped component with the fresh data!
// Notice that we pass through any additional props
return <WrappedComponent data={this.state.data} {...this.props} />;
}
};
}

Note that a HOC doesn’t modify the input component, nor does it use inheritance to copy its behavior. Rather, a HOC composes the original component by wrapping it in a container component. A HOC is a pure function with zero side-effects.


And that’s it! The wrapped component receives all the props of the container, along with a new prop, data , which it uses to render its output. The HOC isn’t concerned with how or why the data is used, and the wrapped component isn’t concerned with where the data came from.


Because withSubscription is a normal function, you can add as many or as few arguments as you like. For example, you may want to make the name of the data prop configurable, to further isolate the HOC from the wrapped component. Or you could accept an argument that configures shouldComponentUpdate , or one that configures the data source. These are all possible because the HOC has full control over how the component is defined.


Like components, the contract between withSubscription and the wrapped component is entirely props-based. This makes it easy to swap one HOC for a different one, as long as they provide the same props to the wrapped component. This may be useful if you change data-fetching libraries, for example.


Don’t Mutate the Original Component. Use Composition.


Resist the temptation to modify a component’s prototype (or otherwise mutate it) inside a HOC.


function logProps(InputComponent) {
InputComponent.prototype.componentDidUpdate = function(prevProps) {
console.log('Current props: ', this.props);
console.log('Previous props: ', prevProps);
};
// The fact that we're returning the original input is a hint that it has
// been mutated.
return InputComponent;
}

// EnhancedComponent will log whenever props are received
const EnhancedComponent = logProps(InputComponent);

There are a few problems with this. One is that the input component cannot be reused separately from the enhanced component. More crucially, if you apply another HOC to EnhancedComponent that also mutates componentDidUpdate , the first HOC’s functionality will be overridden! This HOC also won’t work with function components, which do not have lifecycle methods.


Mutating HOCs are a leaky abstraction—the consumer must know how they are implemented in order to avoid conflicts with other HOCs.


Instead of mutation, HOCs should use composition, by wrapping the input component in a container component:


function logProps(WrappedComponent) {
return class extends React.Component {
componentDidUpdate(prevProps) {
console.log('Current props: ', this.props);
console.log('Previous props: ', prevProps);
}
render() {
// Wraps the input component in a container, without mutating it. Good!
return <WrappedComponent {...this.props} />;
}
}
}

This HOC has the same functionality as the mutating version while avoiding the potential for clashes. It works equally well with class and function components. And because it’s a pure function, it’s composable with other HOCs, or even with itself.


You may have noticed similarities between HOCs and a pattern called container components . Container components are part of a strategy of separating responsibility between high-level and low-level concerns. Containers manage things like subscriptions and state, and pass props to components that handle things like rendering UI. HOCs use containers as part of their implementation. You can think of HOCs as parameterized container component definitions.


Convention: Pass Unrelated Props Through to the Wrapped Component


HOCs add features to a component. They shouldn’t drastically alter its contract. It’s expected that the component returned from a HOC has a similar interface to the wrapped component.


HOCs should pass through props that are unrelated to its specific concern. Most HOCs contain a render method that looks something like this:


render() {
// Filter out extra props that are specific to this HOC and shouldn't be
// passed through
const { extraProp, ...passThroughProps } = this.props;

// Inject props into the wrapped component. These are usually state values or
// instance methods.
const injectedProp = someStateOrInstanceMethod;

// Pass props to wrapped component
return (
<WrappedComponent
injectedProp={injectedProp}
{...passThroughProps}
/>

);
}

This convention helps ensure that HOCs are as flexible and reusable as possible.


Convention: Maximizing Composability


Not all HOCs look the same. Sometimes they accept only a single argument, the wrapped component:


const NavbarWithRouter = withRouter(Navbar);

Usually, HOCs accept additional arguments. In this example from Relay, a config object is used to specify a component’s data dependencies:


const CommentWithRelay = Relay.createContainer(Comment, config);

The most common signature for HOCs looks like this:


// React Redux's `connect`
const ConnectedComment = connect(commentSelector, commentActions)(CommentList);

What?! If you break it apart, it’s easier to see what’s going on.


// connect is a function that returns another function
const enhance = connect(commentListSelector, commentListActions);
// The returned function is a HOC, which returns a component that is connected
// to the Redux store
const ConnectedComment = enhance(CommentList);

In other words, connect is a higher-order function that returns a higher-order component!


This form may seem confusing or unnecessary, but it has a useful property. Single-argument HOCs like the one returned by the connect function have the signature Component => Component . Functions whose output type is the same as its input type are really easy to compose together.


// Instead of doing this...
const EnhancedComponent = withRouter(connect(commentSelector)(WrappedComponent))

// ... you can use a function composition utility
// compose(f, g, h) is the same as (...args) => f(g(h(...args)))
const enhance = compose(
// These are both single-argument HOCs
withRouter,
connect(commentSelector)
)
const EnhancedComponent = enhance(WrappedComponent)

(This same property also allows connect and other enhancer-style HOCs to be used as decorators, an experimental JavaScript proposal.)


The compose utility function is provided by many third-party libraries including lodash (as lodash.flowRight ), Redux, and Ramda.


Convention: Wrap the Display Name for Easy Debugging


The container components created by HOCs show up in the React Developer Tools like any other component. To ease debugging, choose a display name that communicates that it’s the result of a HOC.


The most common technique is to wrap the display name of the wrapped component. So if your higher-order component is named withSubscription , and the wrapped component’s display name is CommentList , use the display name WithSubscription(CommentList) :


function withSubscription(WrappedComponent) {
class WithSubscription extends React.Component {/* ... */}
WithSubscription.displayName = `WithSubscription(${getDisplayName(WrappedComponent)})`;
return WithSubscription;
}

function getDisplayName(WrappedComponent) {
return WrappedComponent.displayName || WrappedComponent.name || 'Component';
}

Caveats


Higher-order components come with a few caveats that aren’t immediately obvious if you’re new to React.


Don’t Use HOCs Inside the render Method


React’s diffing algorithm (called Reconciliation) uses component identity to determine whether it should update the existing subtree or throw it away and mount a new one. If the component returned from render is identical ( === ) to the component from the previous render, React recursively updates the subtree by diffing it with the new one. If they’re not equal, the previous subtree is unmounted completely.


Normally, you shouldn’t need to think about this. But it matters for HOCs because it means you can’t apply a HOC to a component within the render method of a component:


render() {
// A new version of EnhancedComponent is created on every render
// EnhancedComponent1 !== EnhancedComponent2
const EnhancedComponent = enhance(MyComponent);
// That causes the entire subtree to unmount/remount each time!
return <EnhancedComponent />;
}

The problem here isn’t just about performance — remounting a component causes the state of that component and all of its children to be lost.


Instead, apply HOCs outside the component definition so that the resulting component is created only once. Then, its identity will be consistent across renders. This is usually what you want, anyway.


In those rare cases where you need to apply a HOC dynamically, you can also do it inside a component’s lifecycle methods or its constructor.


Static Methods Must Be Copied Over


Sometimes it’s useful to define a static method on a React component. For example, Relay containers expose a static method getFragment to facilitate the composition of GraphQL fragments.


When you apply a HOC to a component, though, the original component is wrapped with a container component. That means the new component does not have any of the static methods of the original component.


// Define a static method
WrappedComponent.staticMethod = function() {/*...*/}
// Now apply a HOC
const EnhancedComponent = enhance(WrappedComponent);

// The enhanced component has no static method
typeof EnhancedComponent.staticMethod === 'undefined' // true

To solve this, you could copy the methods onto the container before returning it:


function enhance(WrappedComponent) {
class Enhance extends React.Component {/*...*/}
// Must know exactly which method(s) to copy :(
Enhance.staticMethod = WrappedComponent.staticMethod;
return Enhance;
}

However, this requires you to know exactly which methods need to be copied. You can use hoist-non-react-statics to automatically copy all non-React static methods:


import hoistNonReactStatic from 'hoist-non-react-statics';
function enhance(WrappedComponent) {
class Enhance extends React.Component {/*...*/}
hoistNonReactStatic(Enhance, WrappedComponent);
return Enhance;
}

Another possible solution is to export the static method separately from the component itself.


// Instead of...
MyComponent.someFunction = someFunction;
export default MyComponent;

// ...export the method separately...
export { someFunction };

// ...and in the consuming module, import both
import MyComponent, { someFunction } from './MyComponent.js';

Refs Aren’t Passed Through


While the convention for higher-order components is to pass through all props to the wrapped component, this does not work for refs. That’s because ref is not really a prop — like key , it’s handled specially by React. If you add a ref to an element whose component is the result of a HOC, the ref refers to an instance of the outermost container component, not the wrapped component.


The solution for this problem is to use the React.forwardRef API (introduced with React 16.3). Learn more about it in the forwarding refs section.

Is this page useful? Edit this page
Read article

Integrating with Other Libraries – React

Integrating with Other Libraries

React can be used in any web application. It can be embedded in other applications and, with a little care, other applications can be embedded in React. This guide will examine some of the more common use cases, focusing on integration with jQuery and Backbone, but the same ideas can be applied to integrating components with any existing code.


Integrating with DOM Manipulation Plugins


React is unaware of changes made to the DOM outside of React. It determines updates based on its own internal representation, and if the same DOM nodes are manipulated by another library, React gets confused and has no way to recover.


This does not mean it is impossible or even necessarily difficult to combine React with other ways of affecting the DOM, you just have to be mindful of what each is doing.


The easiest way to avoid conflicts is to prevent the React component from updating. You can do this by rendering elements that React has no reason to update, like an empty <div /> .


How to Approach the Problem


To demonstrate this, let’s sketch out a wrapper for a generic jQuery plugin.


We will attach a ref to the root DOM element. Inside componentDidMount , we will get a reference to it so we can pass it to the jQuery plugin.


To prevent React from touching the DOM after mounting, we will return an empty <div /> from the render() method. The <div /> element has no properties or children, so React has no reason to update it, leaving the jQuery plugin free to manage that part of the DOM:


class SomePlugin extends React.Component {
componentDidMount() {
this.$el = $(this.el); this.$el.somePlugin(); }

componentWillUnmount() {
this.$el.somePlugin('destroy'); }

render() {
return <div ref={el => this.el = el} />; }
}

Note that we defined both componentDidMount and componentWillUnmount lifecycle methods. Many jQuery plugins attach event listeners to the DOM so it’s important to detach them in componentWillUnmount . If the plugin does not provide a method for cleanup, you will probably have to provide your own, remembering to remove any event listeners the plugin registered to prevent memory leaks.


Integrating with jQuery Chosen Plugin


For a more concrete example of these concepts, let’s write a minimal wrapper for the plugin Chosen, which augments <select> inputs.



Note:


Just because it’s possible, doesn’t mean that it’s the best approach for React apps. We encourage you to use React components when you can. React components are easier to reuse in React applications, and often provide more control over their behavior and appearance.



First, let’s look at what Chosen does to the DOM.


If you call it on a <select> DOM node, it reads the attributes off of the original DOM node, hides it with an inline style, and then appends a separate DOM node with its own visual representation right after the <select> . Then it fires jQuery events to notify us about the changes.


Let’s say that this is the API we’re striving for with our <Chosen> wrapper React component:


function Example() {
return (
<Chosen onChange={value => console.log(value)}>
<option>vanilla</option>
<option>chocolate</option>
<option>strawberry</option>
</Chosen>
);
}

We will implement it as an uncontrolled component for simplicity.


First, we will create an empty component with a render() method where we return <select> wrapped in a <div> :


class Chosen extends React.Component {
render() {
return (
<div> <select className="Chosen-select" ref={el => this.el = el}> {this.props.children}
</select>
</div>
);
}
}

Notice how we wrapped <select> in an extra <div> . This is necessary because Chosen will append another DOM element right after the <select> node we passed to it. However, as far as React is concerned, <div> always only has a single child. This is how we ensure that React updates won’t conflict with the extra DOM node appended by Chosen. It is important that if you modify the DOM outside of React flow, you must ensure React doesn’t have a reason to touch those DOM nodes.


Next, we will implement the lifecycle methods. We need to initialize Chosen with the ref to the <select> node in componentDidMount , and tear it down in componentWillUnmount :


componentDidMount() {
this.$el = $(this.el); this.$el.chosen();}

componentWillUnmount() {
this.$el.chosen('destroy');}

Try it on CodePen


Note that React assigns no special meaning to the this.el field. It only works because we have previously assigned this field from a ref in the render() method:


<select className="Chosen-select" ref={el => this.el = el}>

This is enough to get our component to render, but we also want to be notified about the value changes. To do this, we will subscribe to the jQuery change event on the <select> managed by Chosen.


We won’t pass this.props.onChange directly to Chosen because component’s props might change over time, and that includes event handlers. Instead, we will declare a handleChange() method that calls this.props.onChange , and subscribe it to the jQuery change event:


componentDidMount() {
this.$el = $(this.el);
this.$el.chosen();

this.handleChange = this.handleChange.bind(this); this.$el.on('change', this.handleChange);}

componentWillUnmount() {
this.$el.off('change', this.handleChange); this.$el.chosen('destroy');
}

handleChange(e) { this.props.onChange(e.target.value);}

Try it on CodePen


Finally, there is one more thing left to do. In React, props can change over time. For example, the <Chosen> component can get different children if parent component’s state changes. This means that at integration points it is important that we manually update the DOM in response to prop updates, since we no longer let React manage the DOM for us.


Chosen’s documentation suggests that we can use jQuery trigger() API to notify it about changes to the original DOM element. We will let React take care of updating this.props.children inside <select> , but we will also add a componentDidUpdate() lifecycle method that notifies Chosen about changes in the children list:


componentDidUpdate(prevProps) {
if (prevProps.children !== this.props.children) { this.$el.trigger("chosen:updated"); }
}

This way, Chosen will know to update its DOM element when the <select> children managed by React change.


The complete implementation of the Chosen component looks like this:


class Chosen extends React.Component {
componentDidMount() {
this.$el = $(this.el);
this.$el.chosen();

this.handleChange = this.handleChange.bind(this);
this.$el.on('change', this.handleChange);
}

componentDidUpdate(prevProps) {
if (prevProps.children !== this.props.children) {
this.$el.trigger("chosen:updated");
}
}

componentWillUnmount() {
this.$el.off('change', this.handleChange);
this.$el.chosen('destroy');
}

handleChange(e) {
this.props.onChange(e.target.value);
}

render() {
return (
<div>
<select className="Chosen-select" ref={el => this.el = el}>
{this.props.children}
</select>
</div>
);
}
}

Try it on CodePen


Integrating with Other View Libraries


React can be embedded into other applications thanks to the flexibility of createRoot() .


Although React is commonly used at startup to load a single root React component into the DOM, createRoot() can also be called multiple times for independent parts of the UI which can be as small as a button, or as large as an app.


In fact, this is exactly how React is used at Facebook. This lets us write applications in React piece by piece, and combine them with our existing server-generated templates and other client-side code.


Replacing String-Based Rendering with React


A common pattern in older web applications is to describe chunks of the DOM as a string and insert it into the DOM like so: $el.html(htmlString) . These points in a codebase are perfect for introducing React. Just rewrite the string based rendering as a React component.


So the following jQuery implementation…


$('#container').html('<button id="btn">Say Hello</button>');
$('#btn').click(function() {
alert('Hello!');
});

…could be rewritten using a React component:


function Button() {
return <button id="btn">Say Hello</button>;
}

$('#btn').click(function() {
alert('Hello!');
});

From here you could start moving more logic into the component and begin adopting more common React practices. For example, in components it is best not to rely on IDs because the same component can be rendered multiple times. Instead, we will use the React event system and register the click handler directly on the React <button> element:


function Button(props) {
return <button onClick={props.onClick}>Say Hello</button>;}

function HelloButton() {
function handleClick() { alert('Hello!');
}
return <Button onClick={handleClick} />;}

Try it on CodePen


You can have as many such isolated components as you like, and use ReactDOM.createRoot() to render them to different DOM containers. Gradually, as you convert more of your app to React, you will be able to combine them into larger components, and move some of the ReactDOM.createRoot() calls up the hierarchy.


Embedding React in a Backbone View


Backbone views typically use HTML strings, or string-producing template functions, to create the content for their DOM elements. This process, too, can be replaced with rendering a React component.


Below, we will create a Backbone view called ParagraphView . It will override Backbone’s render() function to render a React <Paragraph> component into the DOM element provided by Backbone ( this.el ). Here, too, we are using ReactDOM.createRoot() :


function Paragraph(props) {
return <p>{props.text}</p>;
}

const ParagraphView = Backbone.View.extend({
initialize(options) {
this.reactRoot = ReactDOM.createRoot(this.el); },
render() {
const text = this.model.get('text');
this.reactRoot.render(<Paragraph text={text} />); return this;
},
remove() {
this.reactRoot.unmount(); Backbone.View.prototype.remove.call(this);
}
});

Try it on CodePen


It is important that we also call root.unmount() in the remove method so that React unregisters event handlers and other resources associated with the component tree when it is detached.


When a component is removed from within a React tree, the cleanup is performed automatically, but because we are removing the entire tree by hand, we must call this method.


Integrating with Model Layers


While it is generally recommended to use unidirectional data flow such as React state, Flux, or Redux, React components can use a model layer from other frameworks and libraries.


Using Backbone Models in React Components


The simplest way to consume Backbone models and collections from a React component is to listen to the various change events and manually force an update.


Components responsible for rendering models would listen to 'change' events, while components responsible for rendering collections would listen for 'add' and 'remove' events. In both cases, call this.forceUpdate() to rerender the component with the new data.


In the example below, the List component renders a Backbone collection, using the Item component to render individual items.


class Item extends React.Component {  constructor(props) {
super(props);
this.handleChange = this.handleChange.bind(this);
}

handleChange() { this.forceUpdate(); }
componentDidMount() {
this.props.model.on('change', this.handleChange); }

componentWillUnmount() {
this.props.model.off('change', this.handleChange); }

render() {
return <li>{this.props.model.get('text')}</li>;
}
}

class List extends React.Component { constructor(props) {
super(props);
this.handleChange = this.handleChange.bind(this);
}

handleChange() { this.forceUpdate(); }
componentDidMount() {
this.props.collection.on('add', 'remove', this.handleChange); }

componentWillUnmount() {
this.props.collection.off('add', 'remove', this.handleChange); }

render() {
return (
<ul>
{this.props.collection.map(model => (
<Item key={model.cid} model={model} /> ))}
</ul>
);
}
}

Try it on CodePen


Extracting Data from Backbone Models


The approach above requires your React components to be aware of the Backbone models and collections. If you later plan to migrate to another data management solution, you might want to concentrate the knowledge about Backbone in as few parts of the code as possible.


One solution to this is to extract the model’s attributes as plain data whenever it changes, and keep this logic in a single place. The following is a higher-order component that extracts all attributes of a Backbone model into state, passing the data to the wrapped component.


This way, only the higher-order component needs to know about Backbone model internals, and most components in the app can stay agnostic of Backbone.


In the example below, we will make a copy of the model’s attributes to form the initial state. We subscribe to the change event (and unsubscribe on unmounting), and when it happens, we update the state with the model’s current attributes. Finally, we make sure that if the model prop itself changes, we don’t forget to unsubscribe from the old model, and subscribe to the new one.


Note that this example is not meant to be exhaustive with regards to working with Backbone, but it should give you an idea for how to approach this in a generic way:


function connectToBackboneModel(WrappedComponent) {  return class BackboneComponent extends React.Component {
constructor(props) {
super(props);
this.state = Object.assign({}, props.model.attributes); this.handleChange = this.handleChange.bind(this);
}

componentDidMount() {
this.props.model.on('change', this.handleChange); }

componentWillReceiveProps(nextProps) {
this.setState(Object.assign({}, nextProps.model.attributes)); if (nextProps.model !== this.props.model) {
this.props.model.off('change', this.handleChange); nextProps.model.on('change', this.handleChange); }
}

componentWillUnmount() {
this.props.model.off('change', this.handleChange); }

handleChange(model) {
this.setState(model.changedAttributes()); }

render() {
const propsExceptModel = Object.assign({}, this.props);
delete propsExceptModel.model;
return <WrappedComponent {...propsExceptModel} {...this.state} />; }
}
}

To demonstrate how to use it, we will connect a NameInput React component to a Backbone model, and update its firstName attribute every time the input changes:


function NameInput(props) {
return (
<p>
<input value={props.firstName} onChange={props.handleChange} /> <br />
My name is {props.firstName}. </p>
);
}

const BackboneNameInput = connectToBackboneModel(NameInput);
function Example(props) {
function handleChange(e) {
props.model.set('firstName', e.target.value); }

return (
<BackboneNameInput model={props.model} handleChange={handleChange} />
);
}

const model = new Backbone.Model({ firstName: 'Frodo' });
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Example model={model} />);

Try it on CodePen


This technique is not limited to Backbone. You can use React with any model library by subscribing to its changes in the lifecycle methods and, optionally, copying the data into the local React state.

Is this page useful? Edit this page
Read article

JSX In Depth – React

JSX In Depth

Fundamentally, JSX just provides syntactic sugar for the React.createElement(component, props, ...children) function. The JSX code:


<MyButton color="blue" shadowSize={2}>
Click Me
</MyButton>

compiles into:


React.createElement(
MyButton,
{color: 'blue', shadowSize: 2},
'Click Me'
)

You can also use the self-closing form of the tag if there are no children. So:


<div className="sidebar" />

compiles into:


React.createElement(
'div',
{className: 'sidebar'}
)

If you want to test out how some specific JSX is converted into JavaScript, you can try out the online Babel compiler.


Specifying The React Element Type


The first part of a JSX tag determines the type of the React element.


Capitalized types indicate that the JSX tag is referring to a React component. These tags get compiled into a direct reference to the named variable, so if you use the JSX <Foo /> expression, Foo must be in scope.


React Must Be in Scope


Since JSX compiles into calls to React.createElement , the React library must also always be in scope from your JSX code.


For example, both of the imports are necessary in this code, even though React and CustomButton are not directly referenced from JavaScript:


import React from 'react';import CustomButton from './CustomButton';
function WarningButton() {
// return React.createElement(CustomButton, {color: 'red'}, null); return <CustomButton color="red" />;
}

If you don’t use a JavaScript bundler and loaded React from a <script> tag, it is already in scope as the React global.


Using Dot Notation for JSX Type


You can also refer to a React component using dot-notation from within JSX. This is convenient if you have a single module that exports many React components. For example, if MyComponents.DatePicker is a component, you can use it directly from JSX with:


import React from 'react';

const MyComponents = {
DatePicker: function DatePicker(props) {
return <div>Imagine a {props.color} datepicker here.</div>;
}
}

function BlueDatePicker() {
return <MyComponents.DatePicker color="blue" />;}

User-Defined Components Must Be Capitalized


When an element type starts with a lowercase letter, it refers to a built-in component like <div> or <span> and results in a string 'div' or 'span' passed to React.createElement . Types that start with a capital letter like <Foo /> compile to React.createElement(Foo) and correspond to a component defined or imported in your JavaScript file.


We recommend naming components with a capital letter. If you do have a component that starts with a lowercase letter, assign it to a capitalized variable before using it in JSX.


For example, this code will not run as expected:


import React from 'react';

// Wrong! This is a component and should have been capitalized:function hello(props) { // Correct! This use of <div> is legitimate because div is a valid HTML tag:
return <div>Hello {props.toWhat}</div>;
}

function HelloWorld() {
// Wrong! React thinks <hello /> is an HTML tag because it's not capitalized: return <hello toWhat="World" />;}

To fix this, we will rename hello to Hello and use <Hello /> when referring to it:


import React from 'react';

// Correct! This is a component and should be capitalized:function Hello(props) { // Correct! This use of <div> is legitimate because div is a valid HTML tag:
return <div>Hello {props.toWhat}</div>;
}

function HelloWorld() {
// Correct! React knows <Hello /> is a component because it's capitalized. return <Hello toWhat="World" />;}

Choosing the Type at Runtime


You cannot use a general expression as the React element type. If you do want to use a general expression to indicate the type of the element, just assign it to a capitalized variable first. This often comes up when you want to render a different component based on a prop:


import React from 'react';
import { PhotoStory, VideoStory } from './stories';

const components = {
photo: PhotoStory,
video: VideoStory
};

function Story(props) {
// Wrong! JSX type can't be an expression. return <components[props.storyType] story={props.story} />;}

To fix this, we will assign the type to a capitalized variable first:


import React from 'react';
import { PhotoStory, VideoStory } from './stories';

const components = {
photo: PhotoStory,
video: VideoStory
};

function Story(props) {
// Correct! JSX type can be a capitalized variable. const SpecificStory = components[props.storyType]; return <SpecificStory story={props.story} />;}

Props in JSX


There are several different ways to specify props in JSX.


JavaScript Expressions as Props


You can pass any JavaScript expression as a prop, by surrounding it with {} . For example, in this JSX:


<MyComponent foo={1 + 2 + 3 + 4} />

For MyComponent , the value of props.foo will be 10 because the expression 1 + 2 + 3 + 4 gets evaluated.


if statements and for loops are not expressions in JavaScript, so they can’t be used in JSX directly. Instead, you can put these in the surrounding code. For example:


function NumberDescriber(props) {
let description;
if (props.number % 2 == 0) { description = <strong>even</strong>; } else { description = <i>odd</i>; } return <div>{props.number} is an {description} number</div>;
}

You can learn more about conditional rendering and loops in the corresponding sections.


String Literals


You can pass a string literal as a prop. These two JSX expressions are equivalent:


<MyComponent message="hello world" />

<MyComponent message={'hello world'} />

When you pass a string literal, its value is HTML-unescaped. So these two JSX expressions are equivalent:


<MyComponent message="&lt;3" />

<MyComponent message={'<3'} />

This behavior is usually not relevant. It’s only mentioned here for completeness.


Props Default to “True”


If you pass no value for a prop, it defaults to true . These two JSX expressions are equivalent:


<MyTextBox autocomplete />

<MyTextBox autocomplete={true} />

In general, we don’t recommend not passing a value for a prop, because it can be confused with the ES6 object shorthand {foo} which is short for {foo: foo} rather than {foo: true} . This behavior is just there so that it matches the behavior of HTML.


Spread Attributes


If you already have props as an object, and you want to pass it in JSX, you can use ... as a “spread” syntax to pass the whole props object. These two components are equivalent:


function App1() {
return <Greeting firstName="Ben" lastName="Hector" />;
}

function App2() {
const props = {firstName: 'Ben', lastName: 'Hector'};
return <Greeting {...props} />;}

You can also pick specific props that your component will consume while passing all other props using the spread syntax.


const Button = props => {
const { kind, ...other } = props; const className = kind === "primary" ? "PrimaryButton" : "SecondaryButton";
return <button className={className} {...other} />;
};

const App = () => {
return (
<div>
<Button kind="primary" onClick={() => console.log("clicked!")}>
Hello World!
</Button>
</div>
);
};

In the example above, the kind prop is safely consumed and is not passed on to the <button> element in the DOM.
All other props are passed via the ...other object making this component really flexible. You can see that it passes an onClick and children props.


Spread attributes can be useful but they also make it easy to pass unnecessary props to components that don’t care about them or to pass invalid HTML attributes to the DOM. We recommend using this syntax sparingly.


Children in JSX


In JSX expressions that contain both an opening tag and a closing tag, the content between those tags is passed as a special prop: props.children . There are several different ways to pass children:


String Literals


You can put a string between the opening and closing tags and props.children will just be that string. This is useful for many of the built-in HTML elements. For example:


<MyComponent>Hello world!</MyComponent>

This is valid JSX, and props.children in MyComponent will simply be the string "Hello world!" . HTML is unescaped, so you can generally write JSX just like you would write HTML in this way:


<div>This is valid HTML &amp; JSX at the same time.</div>

JSX removes whitespace at the beginning and ending of a line. It also removes blank lines. New lines adjacent to tags are removed; new lines that occur in the middle of string literals are condensed into a single space. So these all render to the same thing:


<div>Hello World</div>

<div>
Hello World
</div>

<div>
Hello
World
</div>

<div>

Hello World
</div>

JSX Children


You can provide more JSX elements as the children. This is useful for displaying nested components:


<MyContainer>
<MyFirstComponent />
<MySecondComponent />
</MyContainer>

You can mix together different types of children, so you can use string literals together with JSX children. This is another way in which JSX is like HTML, so that this is both valid JSX and valid HTML:


<div>
Here is a list:
<ul>
<li>Item 1</li>
<li>Item 2</li>
</ul>
</div>

A React component can also return an array of elements:


render() {
// No need to wrap list items in an extra element!
return [
// Don't forget the keys :)
<li key="A">First item</li>,
<li key="B">Second item</li>,
<li key="C">Third item</li>,
];
}

JavaScript Expressions as Children


You can pass any JavaScript expression as children, by enclosing it within {} . For example, these expressions are equivalent:


<MyComponent>foo</MyComponent>

<MyComponent>{'foo'}</MyComponent>

This is often useful for rendering a list of JSX expressions of arbitrary length. For example, this renders an HTML list:


function Item(props) {
return <li>{props.message}</li>;}

function TodoList() {
const todos = ['finish doc', 'submit pr', 'nag dan to review'];
return (
<ul>
{todos.map((message) => <Item key={message} message={message} />)} </ul>
);
}

JavaScript expressions can be mixed with other types of children. This is often useful in lieu of string templates:


function Hello(props) {
return <div>Hello {props.addressee}!</div>;}

Functions as Children


Normally, JavaScript expressions inserted in JSX will evaluate to a string, a React element, or a list of those things. However, props.children works just like any other prop in that it can pass any sort of data, not just the sorts that React knows how to render. For example, if you have a custom component, you could have it take a callback as props.children :


// Calls the children callback numTimes to produce a repeated component
function Repeat(props) {
let items = [];
for (let i = 0; i < props.numTimes; i++) { items.push(props.children(i));
}
return <div>{items}</div>;
}

function ListOfTenThings() {
return (
<Repeat numTimes={10}>
{(index) => <div key={index}>This is item {index} in the list</div>} </Repeat>
);
}

Children passed to a custom component can be anything, as long as that component transforms them into something React can understand before rendering. This usage is not common, but it works if you want to stretch what JSX is capable of.


Booleans, Null, and Undefined Are Ignored


false , null , undefined , and true are valid children. They simply don’t render. These JSX expressions will all render to the same thing:


<div />

<div></div>

<div>{false}</div>

<div>{null}</div>

<div>{undefined}</div>

<div>{true}</div>

This can be useful to conditionally render React elements. This JSX renders the <Header /> component only if showHeader is true :


<div>
{showHeader && <Header />} <Content />
</div>

One caveat is that some “falsy” values, such as the 0 number, are still rendered by React. For example, this code will not behave as you might expect because 0 will be printed when props.messages is an empty array:


<div>
{props.messages.length && <MessageList messages={props.messages} />
}
</div>

To fix this, make sure that the expression before && is always boolean:


<div>
{props.messages.length > 0 && <MessageList messages={props.messages} />
}
</div>

Conversely, if you want a value like false , true , null , or undefined to appear in the output, you have to convert it to a string first:


<div>
My JavaScript variable is {String(myVariable)}.</div>
Is this page useful? Edit this page
Read article

Optimizing Performance – React

Optimizing Performance

Internally, React uses several clever techniques to minimize the number of costly DOM operations required to update the UI. For many applications, using React will lead to a fast user interface without doing much work to specifically optimize for performance. Nevertheless, there are several ways you can speed up your React application.


Use the Production Build


If you’re benchmarking or experiencing performance problems in your React apps, make sure you’re testing with the minified production build.


By default, React includes many helpful warnings. These warnings are very useful in development. However, they make React larger and slower so you should make sure to use the production version when you deploy the app.


If you aren’t sure whether your build process is set up correctly, you can check it by installing React Developer Tools for Chrome. If you visit a site with React in production mode, the icon will have a dark background:







React DevTools on a website with production version of React





If you visit a site with React in development mode, the icon will have a red background:







React DevTools on a website with development version of React





It is expected that you use the development mode when working on your app, and the production mode when deploying your app to the users.


You can find instructions for building your app for production below.


Create React App


If your project is built with Create React App, run:


npm run build

This will create a production build of your app in the build/ folder of your project.


Remember that this is only necessary before deploying to production. For normal development, use npm start .


Single-File Builds


We offer production-ready versions of React and React DOM as single files:


<script src="https://unpkg.com/react@18/umd/react.production.min.js"></script>
<script src="https://unpkg.com/react-dom@18/umd/react-dom.production.min.js"></script>

Remember that only React files ending with .production.min.js are suitable for production.


Brunch


For the most efficient Brunch production build, install the terser-brunch plugin:


# If you use npm
npm install --save-dev terser-brunch

# If you use Yarn
yarn add --dev terser-brunch

Then, to create a production build, add the -p flag to the build command:


brunch build -p

Remember that you only need to do this for production builds. You shouldn’t pass the -p flag or apply this plugin in development, because it will hide useful React warnings and make the builds much slower.


Browserify


For the most efficient Browserify production build, install a few plugins:


# If you use npm
npm install --save-dev envify terser uglifyify

# If you use Yarn
yarn add --dev envify terser uglifyify

To create a production build, make sure that you add these transforms (the order matters) :



  • The envify transform ensures the right build environment is set. Make it global ( -g ).

  • The uglifyify transform removes development imports. Make it global too ( -g ).

  • Finally, the resulting bundle is piped to terser for mangling (read why).


For example:


browserify ./index.js \
-g [ envify --NODE_ENV production ] \
-g uglifyify \
| terser --compress --mangle > ./bundle.js

Remember that you only need to do this for production builds. You shouldn’t apply these plugins in development because they will hide useful React warnings, and make the builds much slower.


Rollup


For the most efficient Rollup production build, install a few plugins:


# If you use npm
npm install --save-dev rollup-plugin-commonjs rollup-plugin-replace rollup-plugin-terser

# If you use Yarn
yarn add --dev rollup-plugin-commonjs rollup-plugin-replace rollup-plugin-terser

To create a production build, make sure that you add these plugins (the order matters) :



  • The replace plugin ensures the right build environment is set.

  • The commonjs plugin provides support for CommonJS in Rollup.

  • The terser plugin compresses and mangles the final bundle.


plugins: [
// ...
require('rollup-plugin-replace')({
'process.env.NODE_ENV': JSON.stringify('production')
}),
require('rollup-plugin-commonjs')(),
require('rollup-plugin-terser')(),
// ...
]

For a complete setup example see this gist.


Remember that you only need to do this for production builds. You shouldn’t apply the terser plugin or the replace plugin with 'production' value in development because they will hide useful React warnings, and make the builds much slower.


webpack



Note:


If you’re using Create React App, please follow the instructions above.

This section is only relevant if you configure webpack directly.



Webpack v4+ will minify your code by default in production mode.


const TerserPlugin = require('terser-webpack-plugin');

module.exports = {
mode: 'production',
optimization: {
minimizer: [new TerserPlugin({ /* additional options here */ })],
},
};

You can learn more about this in webpack documentation.


Remember that you only need to do this for production builds. You shouldn’t apply TerserPlugin in development because it will hide useful React warnings, and make the builds much slower.


Profiling Components with the DevTools Profiler


react-dom 16.5+ and react-native 0.57+ provide enhanced profiling capabilities in DEV mode with the React DevTools Profiler.
An overview of the Profiler can be found in the blog post “Introducing the React Profiler”.
A video walkthrough of the profiler is also available on YouTube.


If you haven’t yet installed the React DevTools, you can find them here:



  • Chrome Browser Extension

  • Firefox Browser Extension

  • Standalone Node Package



Note


A production profiling bundle of react-dom is also available as react-dom/profiling .
Read more about how to use this bundle at fb.me/react-profiling




Note


Before React 17, we use the standard User Timing API to profile components with the chrome performance tab.
For a more detailed walkthrough, check out this article by Ben Schwarz.



Virtualize Long Lists


If your application renders long lists of data (hundreds or thousands of rows), we recommend using a technique known as “windowing”. This technique only renders a small subset of your rows at any given time, and can dramatically reduce the time it takes to re-render the components as well as the number of DOM nodes created.


react-window and react-virtualized are popular windowing libraries. They provide several reusable components for displaying lists, grids, and tabular data. You can also create your own windowing component, like Twitter did, if you want something more tailored to your application’s specific use case.


Avoid Reconciliation


React builds and maintains an internal representation of the rendered UI. It includes the React elements you return from your components. This representation lets React avoid creating DOM nodes and accessing existing ones beyond necessity, as that can be slower than operations on JavaScript objects. Sometimes it is referred to as a “virtual DOM”, but it works the same way on React Native.


When a component’s props or state change, React decides whether an actual DOM update is necessary by comparing the newly returned element with the previously rendered one. When they are not equal, React will update the DOM.


Even though React only updates the changed DOM nodes, re-rendering still takes some time. In many cases it’s not a problem, but if the slowdown is noticeable, you can speed all of this up by overriding the lifecycle function shouldComponentUpdate , which is triggered before the re-rendering process starts. The default implementation of this function returns true , leaving React to perform the update:


shouldComponentUpdate(nextProps, nextState) {
return true;
}

If you know that in some situations your component doesn’t need to update, you can return false from shouldComponentUpdate instead, to skip the whole rendering process, including calling render() on this component and below.


In most cases, instead of writing shouldComponentUpdate() by hand, you can inherit from React.PureComponent . It is equivalent to implementing shouldComponentUpdate() with a shallow comparison of current and previous props and state.


shouldComponentUpdate In Action


Here’s a subtree of components. For each one, SCU indicates what shouldComponentUpdate returned, and vDOMEq indicates whether the rendered React elements were equivalent. Finally, the circle’s color indicates whether the component had to be reconciled or not.







should component update





Since shouldComponentUpdate returned false for the subtree rooted at C2, React did not attempt to render C2, and thus didn’t even have to invoke shouldComponentUpdate on C4 and C5.


For C1 and C3, shouldComponentUpdate returned true , so React had to go down to the leaves and check them. For C6 shouldComponentUpdate returned true , and since the rendered elements weren’t equivalent React had to update the DOM.


The last interesting case is C8. React had to render this component, but since the React elements it returned were equal to the previously rendered ones, it didn’t have to update the DOM.


Note that React only had to do DOM mutations for C6, which was inevitable. For C8, it bailed out by comparing the rendered React elements, and for C2’s subtree and C7, it didn’t even have to compare the elements as we bailed out on shouldComponentUpdate , and render was not called.


Examples


If the only way your component ever changes is when the props.color or the state.count variable changes, you could have shouldComponentUpdate check that:


class CounterButton extends React.Component {
constructor(props) {
super(props);
this.state = {count: 1};
}

shouldComponentUpdate(nextProps, nextState) {
if (this.props.color !== nextProps.color) {
return true;
}
if (this.state.count !== nextState.count) {
return true;
}
return false;
}

render() {
return (
<button
color={this.props.color}
onClick={() => this.setState(state => ({count: state.count + 1}))}>

Count:
{this.state.count}
</button>
);
}
}

In this code, shouldComponentUpdate is just checking if there is any change in props.color or state.count . If those values don’t change, the component doesn’t update. If your component got more complex, you could use a similar pattern of doing a “shallow comparison” between all the fields of props and state to determine if the component should update. This pattern is common enough that React provides a helper to use this logic - just inherit from React.PureComponent . So this code is a simpler way to achieve the same thing:


class CounterButton extends React.PureComponent {
constructor(props) {
super(props);
this.state = {count: 1};
}

render() {
return (
<button
color={this.props.color}
onClick={() => this.setState(state => ({count: state.count + 1}))}>

Count:
{this.state.count}
</button>
);
}
}

Most of the time, you can use React.PureComponent instead of writing your own shouldComponentUpdate . It only does a shallow comparison, so you can’t use it if the props or state may have been mutated in a way that a shallow comparison would miss.


This can be a problem with more complex data structures. For example, let’s say you want a ListOfWords component to render a comma-separated list of words, with a parent WordAdder component that lets you click a button to add a word to the list. This code does not work correctly:


class ListOfWords extends React.PureComponent {
render() {
return <div>{this.props.words.join(',')}</div>;
}
}

class WordAdder extends React.Component {
constructor(props) {
super(props);
this.state = {
words: ['marklar']
};
this.handleClick = this.handleClick.bind(this);
}

handleClick() {
// This section is bad style and causes a bug
const words = this.state.words;
words.push('marklar');
this.setState({words: words});
}

render() {
return (
<div>
<button onClick={this.handleClick} />
<ListOfWords words={this.state.words} />
</div>
);
}
}

The problem is that PureComponent will do a simple comparison between the old and new values of this.props.words . Since this code mutates the words array in the handleClick method of WordAdder , the old and new values of this.props.words will compare as equal, even though the actual words in the array have changed. The ListOfWords will thus not update even though it has new words that should be rendered.


The Power Of Not Mutating Data


The simplest way to avoid this problem is to avoid mutating values that you are using as props or state. For example, the handleClick method above could be rewritten using concat as:


handleClick() {
this.setState(state => ({
words: state.words.concat(['marklar'])
}));
}

ES6 supports a spread syntax for arrays which can make this easier. If you’re using Create React App, this syntax is available by default.


handleClick() {
this.setState(state => ({
words: [...state.words, 'marklar'],
}));
};

You can also rewrite code that mutates objects to avoid mutation, in a similar way. For example, let’s say we have an object named colormap and we want to write a function that changes colormap.right to be 'blue' . We could write:


function updateColorMap(colormap) {
colormap.right = 'blue';
}

To write this without mutating the original object, we can use Object.assign method:


function updateColorMap(colormap) {
return Object.assign({}, colormap, {right: 'blue'});
}

updateColorMap now returns a new object, rather than mutating the old one. Object.assign is in ES6 and requires a polyfill.


Object spread syntax makes it easier to update objects without mutation as well:


function updateColorMap(colormap) {
return {...colormap, right: 'blue'};
}

This feature was added to JavaScript in ES2018.


If you’re using Create React App, both Object.assign and the object spread syntax are available by default.


When you deal with deeply nested objects, updating them in an immutable way can feel convoluted. If you run into this problem, check out Immer or immutability-helper. These libraries let you write highly readable code without losing the benefits of immutability.

Is this page useful? Edit this page
Read article