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

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

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

Portals – React

Portals

Portals provide a first-class way to render children into a DOM node that exists outside the DOM hierarchy of the parent component.


ReactDOM.createPortal(child, container)

The first argument ( child ) is any renderable React child, such as an element, string, or fragment. The second argument ( container ) is a DOM element.


Usage


Normally, when you return an element from a component’s render method, it’s mounted into the DOM as a child of the nearest parent node:


render() {
// React mounts a new div and renders the children into it
return (
<div> {this.props.children}
</div> );
}

However, sometimes it’s useful to insert a child into a different location in the DOM:


render() {
// React does *not* create a new div. It renders the children into `domNode`.
// `domNode` is any valid DOM node, regardless of its location in the DOM.
return ReactDOM.createPortal(
this.props.children,
domNode );
}

A typical use case for portals is when a parent component has an overflow: hidden or z-index style, but you need the child to visually “break out” of its container. For example, dialogs, hovercards, and tooltips.



Note:


When working with portals, remember that managing keyboard focus becomes very important.


For modal dialogs, ensure that everyone can interact with them by following the WAI-ARIA Modal Authoring Practices.



Try it on CodePen


Event Bubbling Through Portals


Even though a portal can be anywhere in the DOM tree, it behaves like a normal React child in every other way. Features like context work exactly the same regardless of whether the child is a portal, as the portal still exists in the React tree regardless of position in the DOM tree .


This includes event bubbling. An event fired from inside a portal will propagate to ancestors in the containing React tree , even if those elements are not ancestors in the DOM tree . Assuming the following HTML structure:


<html>
<body>
<div id="app-root"></div>
<div id="modal-root"></div>
</body>
</html>

A Parent component in #app-root would be able to catch an uncaught, bubbling event from the sibling node #modal-root .


// These two containers are siblings in the DOM
const appRoot = document.getElementById('app-root');
const modalRoot = document.getElementById('modal-root');

class Modal extends React.Component {
constructor(props) {
super(props);
this.el = document.createElement('div');
}

componentDidMount() {
// The portal element is inserted in the DOM tree after
// the Modal's children are mounted, meaning that children
// will be mounted on a detached DOM node. If a child
// component requires to be attached to the DOM tree
// immediately when mounted, for example to measure a
// DOM node, or uses 'autoFocus' in a descendant, add
// state to Modal and only render the children when Modal
// is inserted in the DOM tree.
modalRoot.appendChild(this.el);
}

componentWillUnmount() {
modalRoot.removeChild(this.el);
}

render() {
return ReactDOM.createPortal( this.props.children, this.el ); }
}

class Parent extends React.Component {
constructor(props) {
super(props);
this.state = {clicks: 0};
this.handleClick = this.handleClick.bind(this);
}

handleClick() { // This will fire when the button in Child is clicked, // updating Parent's state, even though button // is not direct descendant in the DOM. this.setState(state => ({ clicks: state.clicks + 1 })); }
render() {
return (
<div onClick={this.handleClick}> <p>Number of clicks: {this.state.clicks}</p>
<p>
Open up the browser DevTools
to observe that the button
is not a child of the div
with the onClick handler.
</p>
<Modal> <Child /> </Modal> </div>
);
}
}

function Child() {
// The click event on this button will bubble up to parent, // because there is no 'onClick' attribute defined return (
<div className="modal">
<button>Click</button> </div>
);
}

const root = ReactDOM.createRoot(appRoot);
root.render(<Parent />);

Try it on CodePen


Catching an event bubbling up from a portal in a parent component allows the development of more flexible abstractions that are not inherently reliant on portals. For example, if you render a <Modal /> component, the parent can capture its events regardless of whether it’s implemented using portals.

Is this page useful? Edit this page
Read article

Profiler API – React

Profiler API

The Profiler measures how often a React application renders and what the “cost” of rendering is.
Its purpose is to help identify parts of an application that are slow and may benefit from optimizations such as memoization.



Note:


Profiling adds some additional overhead, so it is disabled in the production build .


To opt into production profiling, React provides a special production build with profiling enabled.
Read more about how to use this build at fb.me/react-profiling



Usage


A Profiler can be added anywhere in a React tree to measure the cost of rendering that part of the tree.
It requires two props: an id (string) and an onRender callback (function) which React calls any time a component within the tree “commits” an update.


For example, to profile a Navigation component and its descendants:


render(
<App>
<Profiler id="Navigation" onRender={callback}> <Navigation {...props} />
</Profiler>
<Main {...props} />
</App>
);

Multiple Profiler components can be used to measure different parts of an application:


render(
<App>
<Profiler id="Navigation" onRender={callback}> <Navigation {...props} />
</Profiler>
<Profiler id="Main" onRender={callback}> <Main {...props} />
</Profiler>
</App>
);

Profiler components can also be nested to measure different components within the same subtree:


render(
<App>
<Profiler id="Panel" onRender={callback}> <Panel {...props}>
<Profiler id="Content" onRender={callback}> <Content {...props} />
</Profiler>
<Profiler id="PreviewPane" onRender={callback}> <PreviewPane {...props} />
</Profiler>
</Panel>
</Profiler>
</App>
);


Note


Although Profiler is a light-weight component, it should be used only when necessary; each use adds some CPU and memory overhead to an application.



onRender Callback


The Profiler requires an onRender function as a prop.
React calls this function any time a component within the profiled tree “commits” an update.
It receives parameters describing what was rendered and how long it took.


function onRenderCallback(
id, // the "id" prop of the Profiler tree that has just committed
phase, // either "mount" (if the tree just mounted) or "update" (if it re-rendered)
actualDuration, // time spent rendering the committed update
baseDuration, // estimated time to render the entire subtree without memoization
startTime, // when React began rendering this update
commitTime, // when React committed this update
interactions // the Set of interactions belonging to this update
) {
// Aggregate or log render timings...
}

Let’s take a closer look at each of the props:



  • id: string -
    The id prop of the Profiler tree that has just committed.
    This can be used to identify which part of the tree was committed if you are using multiple profilers.

  • phase: "mount" | "update" -
    Identifies whether the tree has just been mounted for the first time or re-rendered due to a change in props, state, or hooks.

  • actualDuration: number -
    Time spent rendering the Profiler and its descendants for the current update.
    This indicates how well the subtree makes use of memoization (e.g. React.memo , useMemo , shouldComponentUpdate ).
    Ideally this value should decrease significantly after the initial mount as many of the descendants will only need to re-render if their specific props change.

  • baseDuration: number -
    Duration of the most recent render time for each individual component within the Profiler tree.
    This value estimates a worst-case cost of rendering (e.g. the initial mount or a tree with no memoization).

  • startTime: number -
    Timestamp when React began rendering the current update.

  • commitTime: number -
    Timestamp when React committed the current update.
    This value is shared between all profilers in a commit, enabling them to be grouped if desirable.

  • interactions: Set -
    Set of “interactions” that were being traced when the update was scheduled (e.g. when render or setState were called).



Note


Interactions can be used to identify the cause of an update, although the API for tracing them is still experimental.


Learn more about it at fb.me/react-interaction-tracing


Is this page useful? Edit this page
Read article

React Without ES6 – React

React Without ES6

Normally you would define a React component as a plain JavaScript class:


class Greeting extends React.Component {
render() {
return <h1>Hello, {this.props.name}</h1>;
}
}

If you don’t use ES6 yet, you may use the create-react-class module instead:


var createReactClass = require('create-react-class');
var Greeting = createReactClass({
render: function() {
return <h1>Hello, {this.props.name}</h1>;
}
});

The API of ES6 classes is similar to createReactClass() with a few exceptions.


Declaring Default Props


With functions and ES6 classes defaultProps is defined as a property on the component itself:


class Greeting extends React.Component {
// ...
}

Greeting.defaultProps = {
name: 'Mary'
};

With createReactClass() , you need to define getDefaultProps() as a function on the passed object:


var Greeting = createReactClass({
getDefaultProps: function() {
return {
name: 'Mary'
};
},

// ...

});

Setting the Initial State


In ES6 classes, you can define the initial state by assigning this.state in the constructor:


class Counter extends React.Component {
constructor(props) {
super(props);
this.state = {count: props.initialCount};
}
// ...
}

With createReactClass() , you have to provide a separate getInitialState method that returns the initial state:


var Counter = createReactClass({
getInitialState: function() {
return {count: this.props.initialCount};
},
// ...
});

Autobinding


In React components declared as ES6 classes, methods follow the same semantics as regular ES6 classes. This means that they don’t automatically bind this to the instance. You’ll have to explicitly use .bind(this) in the constructor:


class SayHello extends React.Component {
constructor(props) {
super(props);
this.state = {message: 'Hello!'};
// This line is important!
this.handleClick = this.handleClick.bind(this);
}

handleClick() {
alert(this.state.message);
}

render() {
// Because `this.handleClick` is bound, we can use it as an event handler.
return (
<button onClick={this.handleClick}>
Say hello
</button>
);
}
}

With createReactClass() , this is not necessary because it binds all methods:


var SayHello = createReactClass({
getInitialState: function() {
return {message: 'Hello!'};
},

handleClick: function() {
alert(this.state.message);
},

render: function() {
return (
<button onClick={this.handleClick}>
Say hello
</button>
);
}
});

This means writing ES6 classes comes with a little more boilerplate code for event handlers, but the upside is slightly better performance in large applications.


If the boilerplate code is too unattractive to you, you may use ES2022 Class Properties syntax:


class SayHello extends React.Component {
constructor(props) {
super(props);
this.state = {message: 'Hello!'};
}

// Using an arrow here binds the method:
handleClick = () => {
alert(this.state.message);
};

render() {
return (
<button onClick={this.handleClick}>
Say hello
</button>
);
}
}

You also have a few other options:



  • Bind methods in the constructor.

  • Use arrow functions, e.g. onClick={(e) => this.handleClick(e)} .

  • Keep using createReactClass .


Mixins



Note:


ES6 launched without any mixin support. Therefore, there is no support for mixins when you use React with ES6 classes.


We also found numerous issues in codebases using mixins, and don’t recommend using them in the new code.


This section exists only for the reference.



Sometimes very different components may share some common functionality. These are sometimes called cross-cutting concerns. createReactClass lets you use a legacy mixins system for that.


One common use case is a component wanting to update itself on a time interval. It’s easy to use setInterval() , but it’s important to cancel your interval when you don’t need it anymore to save memory. React provides lifecycle methods that let you know when a component is about to be created or destroyed. Let’s create a simple mixin that uses these methods to provide an easy setInterval() function that will automatically get cleaned up when your component is destroyed.


var SetIntervalMixin = {
componentWillMount: function() {
this.intervals = [];
},
setInterval: function() {
this.intervals.push(setInterval.apply(null, arguments));
},
componentWillUnmount: function() {
this.intervals.forEach(clearInterval);
}
};

var createReactClass = require('create-react-class');

var TickTock = createReactClass({
mixins: [SetIntervalMixin], // Use the mixin
getInitialState: function() {
return {seconds: 0};
},
componentDidMount: function() {
this.setInterval(this.tick, 1000); // Call a method on the mixin
},
tick: function() {
this.setState({seconds: this.state.seconds + 1});
},
render: function() {
return (
<p>
React has been running for
{this.state.seconds} seconds.
</p>
);
}
});

const root = ReactDOM.createRoot(document.getElementById('example'));
root.render(<TickTock />);

If a component is using multiple mixins and several mixins define the same lifecycle method (i.e. several mixins want to do some cleanup when the component is destroyed), all of the lifecycle methods are guaranteed to be called. Methods defined on mixins run in the order mixins were listed, followed by a method call on the component.

Is this page useful? Edit this page
Read article

React Without JSX – React

React Without JSX

JSX is not a requirement for using React. Using React without JSX is especially convenient when you don’t want to set up compilation in your build environment.


Each JSX element is just syntactic sugar for calling React.createElement(component, props, ...children) . So, anything you can do with JSX can also be done with just plain JavaScript.


For example, this code written with JSX:


class Hello extends React.Component {
render() {
return <div>Hello {this.props.toWhat}</div>;
}
}

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Hello toWhat="World" />);

can be compiled to this code that does not use JSX:


class Hello extends React.Component {
render() {
return React.createElement('div', null, `Hello ${this.props.toWhat}`);
}
}

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(React.createElement(Hello, {toWhat: 'World'}, null));

If you’re curious to see more examples of how JSX is converted to JavaScript, you can try out the online Babel compiler.


The component can either be provided as a string, as a subclass of React.Component , or a plain function.


If you get tired of typing React.createElement so much, one common pattern is to assign a shorthand:


const e = React.createElement;

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(e('div', null, 'Hello World'));

If you use this shorthand form for React.createElement , it can be almost as convenient to use React without JSX.


Alternatively, you can refer to community projects such as react-hyperscript and hyperscript-helpers which offer a terser syntax.

Is this page useful? Edit this page
Read article