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

Static Type Checking – React

Static Type Checking

Static type checkers like Flow and TypeScript identify certain types of problems before you even run your code. They can also improve developer workflow by adding features like auto-completion. For this reason, we recommend using Flow or TypeScript instead of PropTypes for larger code bases.


Flow


Flow is a static type checker for your JavaScript code. It is developed at Facebook and is often used with React. It lets you annotate the variables, functions, and React components with a special type syntax, and catch mistakes early. You can read an introduction to Flow to learn its basics.


To use Flow, you need to:



  • Add Flow to your project as a dependency.

  • Ensure that Flow syntax is stripped from the compiled code.

  • Add type annotations and run Flow to check them.


We will explain these steps below in detail.


Adding Flow to a Project


First, navigate to your project directory in the terminal. You will need to run the following command:


If you use Yarn, run:


yarn add --dev flow-bin

If you use npm, run:


npm install --save-dev flow-bin

This command installs the latest version of Flow into your project.


Now, add flow to the "scripts" section of your package.json to be able to use this from the terminal:


{
// ...
"scripts": {
"flow": "flow", // ...
},
// ...
}

Finally, run one of the following commands:


If you use Yarn, run:


yarn run flow init

If you use npm, run:


npm run flow init

This command will create a Flow configuration file that you will need to commit.


Stripping Flow Syntax from the Compiled Code


Flow extends the JavaScript language with a special syntax for type annotations. However, browsers aren’t aware of this syntax, so we need to make sure it doesn’t end up in the compiled JavaScript bundle that is sent to the browser.


The exact way to do this depends on the tools you use to compile JavaScript.


Create React App


If your project was set up using Create React App, congratulations! The Flow annotations are already being stripped by default so you don’t need to do anything else in this step.


Babel



Note:


These instructions are not for Create React App users. Even though Create React App uses Babel under the hood, it is already configured to understand Flow. Only follow this step if you don’t use Create React App.



If you manually configured Babel for your project, you will need to install a special preset for Flow.


If you use Yarn, run:


yarn add --dev @babel/preset-flow

If you use npm, run:


npm install --save-dev @babel/preset-flow

Then add the flow preset to your Babel configuration. For example, if you configure Babel through .babelrc file, it could look like this:


{
"presets": [
"@babel/preset-flow", "react"
]
}

This will let you use the Flow syntax in your code.



Note:


Flow does not require the react preset, but they are often used together. Flow itself understands JSX syntax out of the box.



Other Build Setups


If you don’t use either Create React App or Babel, you can use flow-remove-types to strip the type annotations.


Running Flow


If you followed the instructions above, you should be able to run Flow for the first time.


yarn flow

If you use npm, run:


npm run flow

You should see a message like:


No errors!
✨ Done in 0.17s.

Adding Flow Type Annotations


By default, Flow only checks the files that include this annotation:


// @flow

Typically it is placed at the top of a file. Try adding it to some files in your project and run yarn flow or npm run flow to see if Flow already found any issues.


There is also an option to force Flow to check all files regardless of the annotation. This can be too noisy for existing projects, but is reasonable for a new project if you want to fully type it with Flow.


Now you’re all set! We recommend to check out the following resources to learn more about Flow:



  • Flow Documentation: Type Annotations

  • Flow Documentation: Editors

  • Flow Documentation: React

  • Linting in Flow


TypeScript


TypeScript is a programming language developed by Microsoft. It is a typed superset of JavaScript, and includes its own compiler. Being a typed language, TypeScript can catch errors and bugs at build time, long before your app goes live. You can learn more about using TypeScript with React here.


To use TypeScript, you need to:



  • Add TypeScript as a dependency to your project

  • Configure the TypeScript compiler options

  • Use the right file extensions

  • Add definitions for libraries you use


Let’s go over these in detail.


Using TypeScript with Create React App


Create React App supports TypeScript out of the box.


To create a new project with TypeScript support, run:


npx create-react-app my-app --template typescript

You can also add it to an existing Create React App project , as documented here.



Note:


If you use Create React App, you can skip the rest of this page . It describes the manual setup which doesn’t apply to Create React App users.



Adding TypeScript to a Project


It all begins with running one command in your terminal.


If you use Yarn, run:


yarn add --dev typescript

If you use npm, run:


npm install --save-dev typescript

Congrats! You’ve installed the latest version of TypeScript into your project. Installing TypeScript gives us access to the tsc command. Before configuration, let’s add tsc to the “scripts” section in our package.json :


{
// ...
"scripts": {
"build": "tsc", // ...
},
// ...
}

Configuring the TypeScript Compiler


The compiler is of no help to us until we tell it what to do. In TypeScript, these rules are defined in a special file called tsconfig.json . To generate this file:


If you use Yarn, run:


yarn run tsc --init

If you use npm, run:


npx tsc --init

Looking at the now generated tsconfig.json , you can see that there are many options you can use to configure the compiler. For a detailed description of all the options, check here.


Of the many options, we’ll look at rootDir and outDir . In its true fashion, the compiler will take in typescript files and generate javascript files. However we don’t want to get confused with our source files and the generated output.


We’ll address this in two steps:



  • Firstly, let’s arrange our project structure like this. We’ll place all our source code in the src directory.


├── package.json
├── src
│ └── index.ts
└── tsconfig.json


  • Next, we’ll tell the compiler where our source code is and where the output should go.


// tsconfig.json

{
"compilerOptions": {
// ...
"rootDir": "src", "outDir": "build" // ...
},
}

Great! Now when we run our build script the compiler will output the generated javascript to the build folder. The TypeScript React Starter provides a tsconfig.json with a good set of rules to get you started.


Generally, you don’t want to keep the generated javascript in your source control, so be sure to add the build folder to your .gitignore .


File extensions


In React, you most likely write your components in a .js file. In TypeScript we have 2 file extensions:


.ts is the default file extension while .tsx is a special extension used for files which contain JSX .


Running TypeScript


If you followed the instructions above, you should be able to run TypeScript for the first time.


yarn build

If you use npm, run:


npm run build

If you see no output, it means that it completed successfully.


Type Definitions


To be able to show errors and hints from other packages, the compiler relies on declaration files. A declaration file provides all the type information about a library. This enables us to use javascript libraries like those on npm in our project.


There are two main ways to get declarations for a library:


Bundled - The library bundles its own declaration file. This is great for us, since all we need to do is install the library, and we can use it right away. To check if a library has bundled types, look for an index.d.ts file in the project. Some libraries will have it specified in their package.json under the typings or types field.


DefinitelyTyped - DefinitelyTyped is a huge repository of declarations for libraries that don’t bundle a declaration file. The declarations are crowd-sourced and managed by Microsoft and open source contributors. React for example doesn’t bundle its own declaration file. Instead we can get it from DefinitelyTyped. To do so enter this command in your terminal.


# yarn
yarn add --dev @types/react

# npm
npm i --save-dev @types/react

Local Declarations
Sometimes the package that you want to use doesn’t bundle declarations nor is it available on DefinitelyTyped. In that case, we can have a local declaration file. To do this, create a declarations.d.ts file in the root of your source directory. A simple declaration could look like this:


declare module 'querystring' {
export function stringify(val: object): string
export function parse(val: string): object
}

You are now ready to code! We recommend to check out the following resources to learn more about TypeScript:



  • TypeScript Documentation: Everyday Types

  • TypeScript Documentation: Migrating from JavaScript

  • TypeScript Documentation: React and Webpack


ReScript


ReScript is a typed language that compiles to JavaScript. Some of its core features are guaranteed 100% type coverage, first-class JSX support and dedicated React bindings to allow integration in existing JS / TS React codebases.


You can find more infos on integrating ReScript in your existing JS / React codebase here.


Kotlin


Kotlin is a statically typed language developed by JetBrains. Its target platforms include the JVM, Android, LLVM, and JavaScript.


JetBrains develops and maintains several tools specifically for the React community: React bindings as well as Create React Kotlin App. The latter helps you start building React apps with Kotlin with no build configuration.


Other Languages


Note there are other statically typed languages that compile to JavaScript and are thus React compatible. For example, F#/Fable with elmish-react. Check out their respective sites for more information, and feel free to add more statically typed languages that work with React to this page!

Is this page useful? Edit this page

Strict Mode – React

Strict Mode

StrictMode is a tool for highlighting potential problems in an application. Like Fragment , StrictMode does not render any visible UI. It activates additional checks and warnings for its descendants.



Note:


Strict mode checks are run in development mode only; they do not impact the production build .



You can enable strict mode for any part of your application. For example:


import React from 'react';

function ExampleApplication() {
return (
<div>
<Header />
<React.StrictMode> <div>
<ComponentOne />
<ComponentTwo />
</div>
</React.StrictMode> <Footer />
</div>
);
}


In the above example, strict mode checks will not be run against the Header and Footer components. However, ComponentOne and ComponentTwo , as well as all of their descendants, will have the checks.


StrictMode currently helps with:



Additional functionality will be added with future releases of React.


Identifying unsafe lifecycles


As explained in this blog post, certain legacy lifecycle methods are unsafe for use in async React applications. However, if your application uses third party libraries, it can be difficult to ensure that these lifecycles aren’t being used. Fortunately, strict mode can help with this!


When strict mode is enabled, React compiles a list of all class components using the unsafe lifecycles, and logs a warning message with information about these components, like so:







strict mode unsafe lifecycles warning





Addressing the issues identified by strict mode now will make it easier for you to take advantage of concurrent rendering in future releases of React.


Warning about legacy string ref API usage


Previously, React provided two ways for managing refs: the legacy string ref API and the callback API. Although the string ref API was the more convenient of the two, it had several downsides and so our official recommendation was to use the callback form instead.


React 16.3 added a third option that offers the convenience of a string ref without any of the downsides:


class MyComponent extends React.Component {
constructor(props) {
super(props);

this.inputRef = React.createRef(); }

render() {
return <input type="text" ref={this.inputRef} />; }

componentDidMount() {
this.inputRef.current.focus(); }
}


Since object refs were largely added as a replacement for string refs, strict mode now warns about usage of string refs.



Note:


Callback refs will continue to be supported in addition to the new createRef API.


You don’t need to replace callback refs in your components. They are slightly more flexible, so they will remain as an advanced feature.



Learn more about the new createRef API here.


Warning about deprecated findDOMNode usage


React used to support findDOMNode to search the tree for a DOM node given a class instance. Normally you don’t need this because you can attach a ref directly to a DOM node.


findDOMNode can also be used on class components but this was breaking abstraction levels by allowing a parent to demand that certain children were rendered. It creates a refactoring hazard where you can’t change the implementation details of a component because a parent might be reaching into its DOM node. findDOMNode only returns the first child, but with the use of Fragments, it is possible for a component to render multiple DOM nodes. findDOMNode is a one time read API. It only gave you an answer when you asked for it. If a child component renders a different node, there is no way to handle this change. Therefore findDOMNode only worked if components always return a single DOM node that never changes.


You can instead make this explicit by passing a ref to your custom component and pass that along to the DOM using ref forwarding.


You can also add a wrapper DOM node in your component and attach a ref directly to it.


class MyComponent extends React.Component {
constructor(props) {
super(props);
this.wrapper = React.createRef(); }
render() {
return <div ref={this.wrapper}>{this.props.children}</div>; }
}


Note:


In CSS, the display: contents attribute can be used if you don’t want the node to be part of the layout.



Detecting unexpected side effects


Conceptually, React does work in two phases:



  • The render phase determines what changes need to be made to e.g. the DOM. During this phase, React calls render and then compares the result to the previous render.

  • The commit phase is when React applies any changes. (In the case of React DOM, this is when React inserts, updates, and removes DOM nodes.) React also calls lifecycles like componentDidMount and componentDidUpdate during this phase.


The commit phase is usually very fast, but rendering can be slow. For this reason, the upcoming concurrent mode (which is not enabled by default yet) breaks the rendering work into pieces, pausing and resuming the work to avoid blocking the browser. This means that React may invoke render phase lifecycles more than once before committing, or it may invoke them without committing at all (because of an error or a higher priority interruption).


Render phase lifecycles include the following class component methods:



  • constructor

  • componentWillMount (or UNSAFE_componentWillMount )

  • componentWillReceiveProps (or UNSAFE_componentWillReceiveProps )

  • componentWillUpdate (or UNSAFE_componentWillUpdate )

  • getDerivedStateFromProps

  • shouldComponentUpdate

  • render

  • setState updater functions (the first argument)


Because the above methods might be called more than once, it’s important that they do not contain side-effects. Ignoring this rule can lead to a variety of problems, including memory leaks and invalid application state. Unfortunately, it can be difficult to detect these problems as they can often be non-deterministic.


Strict mode can’t automatically detect side effects for you, but it can help you spot them by making them a little more deterministic. This is done by intentionally double-invoking the following functions:



  • Class component constructor , render , and shouldComponentUpdate methods

  • Class component static getDerivedStateFromProps method

  • Function component bodies

  • State updater functions (the first argument to setState )

  • Functions passed to useState , useMemo , or useReducer



Note:


This only applies to development mode. Lifecycles will not be double-invoked in production mode.



For example, consider the following code:


class TopLevelRoute extends React.Component {
constructor(props) {
super(props);

SharedApplicationState.recordEvent('ExampleComponent');
}
}


At first glance, this code might not seem problematic. But if SharedApplicationState.recordEvent is not idempotent, then instantiating this component multiple times could lead to invalid application state. This sort of subtle bug might not manifest during development, or it might do so inconsistently and so be overlooked.


By intentionally double-invoking methods like the component constructor, strict mode makes patterns like this easier to spot.



Note:


In React 17, React automatically modifies the console methods like console.log() to silence the logs in the second call to lifecycle functions. However, it may cause undesired behavior in certain cases where a workaround can be used.


Starting from React 18, React does not suppress any logs. However, if you have React DevTools installed, the logs from the second call will appear slightly dimmed. React DevTools also offers a setting (off by default) to suppress them completely.



Detecting legacy context API


The legacy context API is error-prone, and will be removed in a future major version. It still works for all 16.x releases but will show this warning message in strict mode:







warn legacy context in strict mode





Read the new context API documentation to help migrate to the new version.


Ensuring reusable state


In the future, we’d like to add a feature that allows React to add and remove sections of the UI while preserving state. For example, when a user tabs away from a screen and back, React should be able to immediately show the previous screen. To do this, React will support remounting trees using the same component state used before unmounting.


This feature will give React better performance out-of-the-box, but requires components to be resilient to effects being mounted and destroyed multiple times. Most effects will work without any changes, but some effects do not properly clean up subscriptions in the destroy callback, or implicitly assume they are only mounted or destroyed once.


To help surface these issues, React 18 introduces a new development-only check to Strict Mode. This new check will automatically unmount and remount every component, whenever a component mounts for the first time, restoring the previous state on the second mount.


To demonstrate the development behavior you’ll see in Strict Mode with this feature, consider what happens when React mounts a new component. Without this change, when a component mounts, React creates the effects:


* React mounts the component.
* Layout effects are created.
* Effects are created.

With Strict Mode starting in React 18, whenever a component mounts in development, React will simulate immediately unmounting and remounting the component:


* React mounts the component.
* Layout effects are created.
* Effect effects are created.
* React simulates effects being destroyed on a mounted component.
* Layout effects are destroyed.
* Effects are destroyed.
* React simulates effects being re-created on a mounted component.
* Layout effects are created
* Effect setup code runs

On the second mount, React will restore the state from the first mount. This feature simulates user behavior such as a user tabbing away from a screen and back, ensuring that code will properly handle state restoration.


When the component unmounts, effects are destroyed as normal:


* React unmounts the component.
* Layout effects are destroyed.
* Effect effects are destroyed.

Unmounting and remounting includes:



  • componentDidMount

  • componentWillUnmount

  • useEffect

  • useLayoutEffect

  • useInsertionEffect



Note:


This only applies to development mode, production behavior is unchanged .



For help supporting common issues, see:



  • How to support Reusable State in Effects

Is this page useful? Edit this page
Read article

Typechecking With PropTypes – React

Typechecking With PropTypes


Note:


React.PropTypes has moved into a different package since React v15.5. Please use the prop-types library instead.


We provide a codemod script to automate the conversion.



As your app grows, you can catch a lot of bugs with typechecking. For some applications, you can use JavaScript extensions like Flow or TypeScript to typecheck your whole application. But even if you don’t use those, React has some built-in typechecking abilities. To run typechecking on the props for a component, you can assign the special propTypes property:


import PropTypes from 'prop-types';

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

Greeting.propTypes = {
name: PropTypes.string
};

In this example, we are using a class component, but the same functionality could also be applied to function components, or components created by React.memo or React.forwardRef .


PropTypes exports a range of validators that can be used to make sure the data you receive is valid. In this example, we’re using PropTypes.string . When an invalid value is provided for a prop, a warning will be shown in the JavaScript console. For performance reasons, propTypes is only checked in development mode.


PropTypes


Here is an example documenting the different validators provided:


import PropTypes from 'prop-types';

MyComponent.propTypes = {
// You can declare that a prop is a specific JS type. By default, these
// are all optional.
optionalArray: PropTypes.array,
optionalBool: PropTypes.bool,
optionalFunc: PropTypes.func,
optionalNumber: PropTypes.number,
optionalObject: PropTypes.object,
optionalString: PropTypes.string,
optionalSymbol: PropTypes.symbol,

// Anything that can be rendered: numbers, strings, elements or an array
// (or fragment) containing these types.
optionalNode: PropTypes.node,

// A React element.
optionalElement: PropTypes.element,

// A React element type (ie. MyComponent).
optionalElementType: PropTypes.elementType,

// You can also declare that a prop is an instance of a class. This uses
// JS's instanceof operator.
optionalMessage: PropTypes.instanceOf(Message),

// You can ensure that your prop is limited to specific values by treating
// it as an enum.
optionalEnum: PropTypes.oneOf(['News', 'Photos']),

// An object that could be one of many types
optionalUnion: PropTypes.oneOfType([
PropTypes.string,
PropTypes.number,
PropTypes.instanceOf(Message)
]),

// An array of a certain type
optionalArrayOf: PropTypes.arrayOf(PropTypes.number),

// An object with property values of a certain type
optionalObjectOf: PropTypes.objectOf(PropTypes.number),

// An object taking on a particular shape
optionalObjectWithShape: PropTypes.shape({
color: PropTypes.string,
fontSize: PropTypes.number
}),

// An object with warnings on extra properties
optionalObjectWithStrictShape: PropTypes.exact({
name: PropTypes.string,
quantity: PropTypes.number
}),

// You can chain any of the above with `isRequired` to make sure a warning
// is shown if the prop isn't provided.
requiredFunc: PropTypes.func.isRequired,

// A required value of any data type
requiredAny: PropTypes.any.isRequired,

// You can also specify a custom validator. It should return an Error
// object if the validation fails. Don't `console.warn` or throw, as this
// won't work inside `oneOfType`.
customProp: function(props, propName, componentName) {
if (!/matchme/.test(props[propName])) {
return new Error(
'Invalid prop `' + propName + '` supplied to' +
' `' + componentName + '`. Validation failed.'
);
}
},

// You can also supply a custom validator to `arrayOf` and `objectOf`.
// It should return an Error object if the validation fails. The validator
// will be called for each key in the array or object. The first two
// arguments of the validator are the array or object itself, and the
// current item's key.
customArrayProp: PropTypes.arrayOf(function(propValue, key, componentName, location, propFullName) {
if (!/matchme/.test(propValue[key])) {
return new Error(
'Invalid prop `' + propFullName + '` supplied to' +
' `' + componentName + '`. Validation failed.'
);
}
})
};

Requiring Single Child


With PropTypes.element you can specify that only a single child can be passed to a component as children.


import PropTypes from 'prop-types';

class MyComponent extends React.Component {
render() {
// This must be exactly one element or it will warn.
const children = this.props.children;
return (
<div>
{children}
</div>
);
}
}

MyComponent.propTypes = {
children: PropTypes.element.isRequired
};

Default Prop Values


You can define default values for your props by assigning to the special defaultProps property:


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

// Specifies the default values for props:
Greeting.defaultProps = {
name: 'Stranger'
};

// Renders "Hello, Stranger":
const root = ReactDOM.createRoot(document.getElementById('example'));
root.render(<Greeting />);

Since ES2022 you can also declare defaultProps as static property within a React component class. For more information, see the class public static fields. This modern syntax will require a compilation step to work within older browsers.


class Greeting extends React.Component {
static defaultProps = {
name: 'stranger'
}

render() {
return (
<div>Hello, {this.props.name}</div>
)
}
}

The defaultProps will be used to ensure that this.props.name will have a value if it was not specified by the parent component. The propTypes typechecking happens after defaultProps are resolved, so typechecking will also apply to the defaultProps .


Function Components


If you are using function components in your regular development, you may want to make some small changes to allow PropTypes to be properly applied.


Let’s say you have a component like this:


export default function HelloWorldComponent({ name }) {
return (
<div>Hello, {name}</div>
)
}

To add PropTypes, you may want to declare the component in a separate function before exporting, like this:


function HelloWorldComponent({ name }) {
return (
<div>Hello, {name}</div>
)
}

export default HelloWorldComponent

Then, you can add PropTypes directly to the HelloWorldComponent :


import PropTypes from 'prop-types'

function HelloWorldComponent({ name }) {
return (
<div>Hello, {name}</div>
)
}

HelloWorldComponent.propTypes = {
name: PropTypes.string
}

export default HelloWorldComponent
Is this page useful? Edit this page
Read article

Uncontrolled Components – React

Uncontrolled Components

In most cases, we recommend using controlled components to implement forms. In a controlled component, form data is handled by a React component. The alternative is uncontrolled components, where form data is handled by the DOM itself.


To write an uncontrolled component, instead of writing an event handler for every state update, you can use a ref to get form values from the DOM.


For example, this code accepts a single name in an uncontrolled component:


class NameForm extends React.Component {
constructor(props) {
super(props);
this.handleSubmit = this.handleSubmit.bind(this);
this.input = React.createRef(); }

handleSubmit(event) {
alert('A name was submitted: ' + this.input.current.value); event.preventDefault();
}

render() {
return (
<form onSubmit={this.handleSubmit}>
<label>
Name:
<input type="text" ref={this.input} /> </label>
<input type="submit" value="Submit" />
</form>
);
}
}

Try it on CodePen


Since an uncontrolled component keeps the source of truth in the DOM, it is sometimes easier to integrate React and non-React code when using uncontrolled components. It can also be slightly less code if you want to be quick and dirty. Otherwise, you should usually use controlled components.


If it’s still not clear which type of component you should use for a particular situation, you might find this article on controlled versus uncontrolled inputs to be helpful.


Default Values


In the React rendering lifecycle, the value attribute on form elements will override the value in the DOM. With an uncontrolled component, you often want React to specify the initial value, but leave subsequent updates uncontrolled. To handle this case, you can specify a defaultValue attribute instead of value . Changing the value of defaultValue attribute after a component has mounted will not cause any update of the value in the DOM.


render() {
return (
<form onSubmit={this.handleSubmit}>
<label>
Name:
<input
defaultValue="Bob" type="text"
ref={this.input} />

</label>
<input type="submit" value="Submit" />
</form>
);
}

Likewise, <input type="checkbox"> and <input type="radio"> support defaultChecked , and <select> and <textarea> supports defaultValue .


The file input Tag


In HTML, an <input type="file"> lets the user choose one or more files from their device storage to be uploaded to a server or manipulated by JavaScript via the File API.


<input type="file" />

In React, an <input type="file" /> is always an uncontrolled component because its value can only be set by a user, and not programmatically.


You should use the File API to interact with the files. The following example shows how to create a ref to the DOM node to access file(s) in a submit handler:



class FileInput extends React.Component {
constructor(props) {
super(props);
this.handleSubmit = this.handleSubmit.bind(this);
this.fileInput = React.createRef(); }
handleSubmit(event) {
event.preventDefault();
alert(
`Selected file - ${this.fileInput.current.files[0].name}` );
}

render() {
return (
<form onSubmit={this.handleSubmit}>
<label>
Upload file:
<input type="file" ref={this.fileInput} /> </label>
<br />
<button type="submit">Submit</button>
</form>
);
}
}

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


Try it on CodePen

Is this page useful? Edit this page
Read article

Web Components – React

Web Components

React and Web Components are built to solve different problems. Web Components provide strong encapsulation for reusable components, while React provides a declarative library that keeps the DOM in sync with your data. The two goals are complementary. As a developer, you are free to use React in your Web Components, or to use Web Components in React, or both.


Most people who use React don’t use Web Components, but you may want to, especially if you are using third-party UI components that are written using Web Components.


Using Web Components in React


class HelloMessage extends React.Component {
render() {
return <div>Hello <x-search>{this.props.name}</x-search>!</div>;
}
}


Note:


Web Components often expose an imperative API. For instance, a video Web Component might expose play() and pause() functions. To access the imperative APIs of a Web Component, you will need to use a ref to interact with the DOM node directly. If you are using third-party Web Components, the best solution is to write a React component that behaves as a wrapper for your Web Component.


Events emitted by a Web Component may not properly propagate through a React render tree.
You will need to manually attach event handlers to handle these events within your React components.



One common confusion is that Web Components use “class” instead of “className”.


function BrickFlipbox() {
return (
<brick-flipbox class="demo">
<div>front</div>
<div>back</div>
</brick-flipbox>
);
}

Using React in your Web Components


class XSearch extends HTMLElement {
connectedCallback() {
const mountPoint = document.createElement('span');
this.attachShadow({ mode: 'open' }).appendChild(mountPoint);

const name = this.getAttribute('name');
const url = 'https://www.google.com/search?q=' + encodeURIComponent(name);
const root = ReactDOM.createRoot(mountPoint);
root.render(<a href={url}>{name}</a>);
}
}
customElements.define('x-search', XSearch);


Note:


This code will not work if you transform classes with Babel. See this issue for the discussion.
Include the custom-elements-es5-adapter before you load your web components to fix this issue.


Is this page useful? Edit this page
Read article

React Top-Level API – React

React Top-Level API

React is the entry point to the React library. If you load React from a <script> tag, these top-level APIs are available on the React global. If you use ES6 with npm, you can write import React from 'react' . If you use ES5 with npm, you can write var React = require('react') .


Overview


Components


React components let you split the UI into independent, reusable pieces, and think about each piece in isolation. React components can be defined by subclassing React.Component or React.PureComponent .



  • React.Component

  • React.PureComponent


If you don’t use ES6 classes, you may use the create-react-class module instead. See Using React without ES6 for more information.


React components can also be defined as functions which can be wrapped:



  • React.memo


Creating React Elements


We recommend using JSX to describe what your UI should look like. Each JSX element is just syntactic sugar for calling React.createElement() . You will not typically invoke the following methods directly if you are using JSX.



  • createElement()

  • createFactory()


See Using React without JSX for more information.


Transforming Elements


React provides several APIs for manipulating elements:



  • cloneElement()

  • isValidElement()

  • React.Children


Fragments


React also provides a component for rendering multiple elements without a wrapper.



  • React.Fragment


Refs



  • React.createRef

  • React.forwardRef


Suspense


Suspense lets components “wait” for something before rendering. Today, Suspense only supports one use case: loading components dynamically with React.lazy . In the future, it will support other use cases like data fetching.



  • React.lazy

  • React.Suspense


Transitions


Transitions are a new concurrent feature introduced in React 18. They allow you to mark updates as transitions, which tells React that they can be interrupted and avoid going back to Suspense fallbacks for already visible content.



  • React.startTransition

  • React.useTransition


Hooks


Hooks are a new addition in React 16.8. They let you use state and other React features without writing a class. Hooks have a dedicated docs section and a separate API reference:




  • Basic Hooks



    • useState

    • useEffect

    • useContext




  • Additional Hooks



    • useReducer

    • useCallback

    • useMemo

    • useRef

    • useImperativeHandle

    • useLayoutEffect

    • useDebugValue

    • useDeferredValue

    • useTransition

    • useId




  • Library Hooks



    • useSyncExternalStore

    • useInsertionEffect






Reference


React.Component


React.Component is the base class for React components when they are defined using ES6 classes:


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

See the React.Component API Reference for a list of methods and properties related to the base React.Component class.




React.PureComponent


React.PureComponent is similar to React.Component . The difference between them is that React.Component doesn’t implement shouldComponentUpdate() , but React.PureComponent implements it with a shallow prop and state comparison.


If your React component’s render() function renders the same result given the same props and state, you can use React.PureComponent for a performance boost in some cases.



Note


React.PureComponent ’s shouldComponentUpdate() only shallowly compares the objects. If these contain complex data structures, it may produce false-negatives for deeper differences. Only extend PureComponent when you expect to have simple props and state, or use forceUpdate() when you know deep data structures have changed. Or, consider using immutable objects to facilitate fast comparisons of nested data.


Furthermore, React.PureComponent ’s shouldComponentUpdate() skips prop updates for the whole component subtree. Make sure all the children components are also “pure”.





React.memo


const MyComponent = React.memo(function MyComponent(props) {
/* render using props */
});

React.memo is a higher order component.


If your component renders the same result given the same props, you can wrap it in a call to React.memo for a performance boost in some cases by memoizing the result. This means that React will skip rendering the component, and reuse the last rendered result.


React.memo only checks for prop changes. If your function component wrapped in React.memo has a useState , useReducer or useContext Hook in its implementation, it will still rerender when state or context change.


By default it will only shallowly compare complex objects in the props object. If you want control over the comparison, you can also provide a custom comparison function as the second argument.


function MyComponent(props) {
/* render using props */
}
function areEqual(prevProps, nextProps) {
/*
return true if passing nextProps to render would return
the same result as passing prevProps to render,
otherwise return false
*/

}
export default React.memo(MyComponent, areEqual);

This method only exists as a performance optimization. Do not rely on it to “prevent” a render, as this can lead to bugs.



Note


Unlike the shouldComponentUpdate() method on class components, the areEqual function returns true if the props are equal and false if the props are not equal. This is the inverse from shouldComponentUpdate .





createElement()


React.createElement(
type,
[props],
[...children]
)

Create and return a new React element of the given type. The type argument can be either a tag name string (such as 'div' or 'span' ), a React component type (a class or a function), or a React fragment type.


Code written with JSX will be converted to use React.createElement() . You will not typically invoke React.createElement() directly if you are using JSX. See React Without JSX to learn more.




cloneElement()


React.cloneElement(
element,
[config],
[...children]
)

Clone and return a new React element using element as the starting point. config should contain all new props, key , or ref . The resulting element will have the original element’s props with the new props merged in shallowly. New children will replace existing children. key and ref from the original element will be preserved if no key and ref present in the config .


React.cloneElement() is almost equivalent to:


<element.type {...element.props} {...props}>{children}</element.type>

However, it also preserves ref s. This means that if you get a child with a ref on it, you won’t accidentally steal it from your ancestor. You will get the same ref attached to your new element. The new ref or key will replace old ones if present.


This API was introduced as a replacement of the deprecated React.addons.cloneWithProps() .




createFactory()


React.createFactory(type)

Return a function that produces React elements of a given type. Like React.createElement() , the type argument can be either a tag name string (such as 'div' or 'span' ), a React component type (a class or a function), or a React fragment type.


This helper is considered legacy, and we encourage you to either use JSX or use React.createElement() directly instead.


You will not typically invoke React.createFactory() directly if you are using JSX. See React Without JSX to learn more.




isValidElement()


React.isValidElement(object)

Verifies the object is a React element. Returns true or false .




React.Children


React.Children provides utilities for dealing with the this.props.children opaque data structure.


React.Children.map


React.Children.map(children, function[(thisArg)])

Invokes a function on every immediate child contained within children with this set to thisArg . If children is an array it will be traversed and the function will be called for each child in the array. If children is null or undefined , this method will return null or undefined rather than an array.



Note


If children is a Fragment it will be treated as a single child and not traversed.



React.Children.forEach


React.Children.forEach(children, function[(thisArg)])

Like React.Children.map() but does not return an array.


React.Children.count


React.Children.count(children)

Returns the total number of components in children , equal to the number of times that a callback passed to map or forEach would be invoked.


React.Children.only


React.Children.only(children)

Verifies that children has only one child (a React element) and returns it. Otherwise this method throws an error.



Note:


React.Children.only() does not accept the return value of React.Children.map() because it is an array rather than a React element.



React.Children.toArray


React.Children.toArray(children)

Returns the children opaque data structure as a flat array with keys assigned to each child. Useful if you want to manipulate collections of children in your render methods, especially if you want to reorder or slice this.props.children before passing it down.



Note:


React.Children.toArray() changes keys to preserve the semantics of nested arrays when flattening lists of children. That is, toArray prefixes each key in the returned array so that each element’s key is scoped to the input array containing it.





React.Fragment


The React.Fragment component lets you return multiple elements in a render() method without creating an additional DOM element:


render() {
return (
<React.Fragment>
Some text.
<h2>A heading</h2>
</React.Fragment>
);
}

You can also use it with the shorthand <></> syntax. For more information, see React v16.2.0: Improved Support for Fragments.


React.createRef


React.createRef creates a ref that can be attached to React elements via the ref attribute.


class MyComponent extends React.Component {
constructor(props) {
super(props);

this.inputRef = React.createRef(); }

render() {
return <input type="text" ref={this.inputRef} />; }

componentDidMount() {
this.inputRef.current.focus(); }
}


React.forwardRef


React.forwardRef creates a React component that forwards the ref attribute it receives to another component below in the tree. This technique is not very common but is particularly useful in two scenarios:



  • Forwarding refs to DOM components

  • Forwarding refs in higher-order-components


React.forwardRef accepts a rendering function as an argument. React will call this function with props and ref as two arguments. This function should return a React node.



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>;


In the above example, React passes a ref given to <FancyButton ref={ref}> element as a second argument to the rendering function inside the React.forwardRef call. This rendering function passes the ref to the <button ref={ref}> element.


As a result, after React attaches the ref, ref.current will point directly to the <button> DOM element instance.


For more information, see forwarding refs.


React.lazy


React.lazy() lets you define a component that is loaded dynamically. This helps reduce the bundle size to delay loading components that aren’t used during the initial render.


You can learn how to use it from our code splitting documentation. You might also want to check out this article explaining how to use it in more detail.


// This component is loaded dynamically
const SomeComponent = React.lazy(() => import('./SomeComponent'));

Note that rendering lazy components requires that there’s a <React.Suspense> component higher in the rendering tree. This is how you specify a loading indicator.


React.Suspense


React.Suspense lets you specify the loading indicator in case some components in the tree below it are not yet ready to render. In the future we plan to let Suspense handle more scenarios such as data fetching. You can read about this in our roadmap.


Today, lazy loading components is the only use case supported by <React.Suspense> :


// This component is loaded dynamically
const OtherComponent = React.lazy(() => import('./OtherComponent'));

function MyComponent() {
return (
// Displays <Spinner> until OtherComponent loads
<React.Suspense fallback={<Spinner />}>
<div>
<OtherComponent />
</div>
</React.Suspense>
);
}

It is documented in our code splitting guide. Note that lazy components can be deep inside the Suspense tree — it doesn’t have to wrap every one of them. The best practice is to place <Suspense> where you want to see a loading indicator, but to use lazy() wherever you want to do code splitting.



Note


For content that is already shown to the user, switching back to a loading indicator can be disorienting. It is sometimes better to show the “old” UI while the new UI is being prepared. To do this, you can use the new transition APIs startTransition and useTransition to mark updates as transitions and avoid unexpected fallbacks.



React.Suspense in Server Side Rendering


During server side rendering Suspense Boundaries allow you to flush your application in smaller chunks by suspending.
When a component suspends we schedule a low priority task to render the closest Suspense boundary’s fallback. If the component unsuspends before we flush the fallback then we send down the actual content and throw away the fallback.


React.Suspense during hydration


Suspense boundaries depend on their parent boundaries being hydrated before they can hydrate, but they can hydrate independently from sibling boundaries. Events on a boundary before it is hydrated will cause the boundary to hydrate at a higher priority than neighboring boundaries. Read more


React.startTransition


React.startTransition(callback)

React.startTransition lets you mark updates inside the provided callback as transitions. This method is designed to be used when React.useTransition is not available.



Note:


Updates in a transition yield to more urgent updates such as clicks.


Updates in a transition will not show a fallback for re-suspended content, allowing the user to continue interacting while rendering the update.


React.startTransition does not provide an isPending flag. To track the pending status of a transition see React.useTransition .


Is this page useful? Edit this page
Read article