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
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
Reconciliation – React

Reconciliation

React provides a declarative API so that you don’t have to worry about exactly what changes on every update. This makes writing applications a lot easier, but it might not be obvious how this is implemented within React. This article explains the choices we made in React’s “diffing” algorithm so that component updates are predictable while being fast enough for high-performance apps.


Motivation


When you use React, at a single point in time you can think of the render() function as creating a tree of React elements. On the next state or props update, that render() function will return a different tree of React elements. React then needs to figure out how to efficiently update the UI to match the most recent tree.


There are some generic solutions to this algorithmic problem of generating the minimum number of operations to transform one tree into another. However, the state of the art algorithms have a complexity in the order of O(n 3 ) where n is the number of elements in the tree.


If we used this in React, displaying 1000 elements would require in the order of one billion comparisons. This is far too expensive. Instead, React implements a heuristic O(n) algorithm based on two assumptions:



  1. Two elements of different types will produce different trees.

  2. The developer can hint at which child elements may be stable across different renders with a key prop.


In practice, these assumptions are valid for almost all practical use cases.


The Diffing Algorithm


When diffing two trees, React first compares the two root elements. The behavior is different depending on the types of the root elements.


Elements Of Different Types


Whenever the root elements have different types, React will tear down the old tree and build the new tree from scratch. Going from <a> to <img> , or from <Article> to <Comment> , or from <Button> to <div> - any of those will lead to a full rebuild.


When tearing down a tree, old DOM nodes are destroyed. Component instances receive componentWillUnmount() . When building up a new tree, new DOM nodes are inserted into the DOM. Component instances receive UNSAFE_componentWillMount() and then componentDidMount() . Any state associated with the old tree is lost.


Any components below the root will also get unmounted and have their state destroyed. For example, when diffing:


<div>
<Counter />
</div>

<span>
<Counter />
</span>

This will destroy the old Counter and remount a new one.



Note:


This method is considered legacy and you should avoid it in new code:



  • UNSAFE_componentWillMount()



DOM Elements Of The Same Type


When comparing two React DOM elements of the same type, React looks at the attributes of both, keeps the same underlying DOM node, and only updates the changed attributes. For example:


<div className="before" title="stuff" />

<div className="after" title="stuff" />

By comparing these two elements, React knows to only modify the className on the underlying DOM node.


When updating style , React also knows to update only the properties that changed. For example:


<div style={{color: 'red', fontWeight: 'bold'}} />

<div style={{color: 'green', fontWeight: 'bold'}} />

When converting between these two elements, React knows to only modify the color style, not the fontWeight .


After handling the DOM node, React then recurses on the children.


Component Elements Of The Same Type


When a component updates, the instance stays the same, so that state is maintained across renders. React updates the props of the underlying component instance to match the new element, and calls UNSAFE_componentWillReceiveProps() , UNSAFE_componentWillUpdate() and componentDidUpdate() on the underlying instance.


Next, the render() method is called and the diff algorithm recurses on the previous result and the new result.



Note:


These methods are considered legacy and you should avoid them in new code:



  • UNSAFE_componentWillUpdate()

  • UNSAFE_componentWillReceiveProps()



Recursing On Children


By default, when recursing on the children of a DOM node, React just iterates over both lists of children at the same time and generates a mutation whenever there’s a difference.


For example, when adding an element at the end of the children, converting between these two trees works well:


<ul>
<li>first</li>
<li>second</li>
</ul>

<ul>
<li>first</li>
<li>second</li>
<li>third</li>
</ul>

React will match the two <li>first</li> trees, match the two <li>second</li> trees, and then insert the <li>third</li> tree.


If you implement it naively, inserting an element at the beginning has worse performance. For example, converting between these two trees works poorly:


<ul>
<li>Duke</li>
<li>Villanova</li>
</ul>

<ul>
<li>Connecticut</li>
<li>Duke</li>
<li>Villanova</li>
</ul>

React will mutate every child instead of realizing it can keep the <li>Duke</li> and <li>Villanova</li> subtrees intact. This inefficiency can be a problem.


Keys


In order to solve this issue, React supports a key attribute. When children have keys, React uses the key to match children in the original tree with children in the subsequent tree. For example, adding a key to our inefficient example above can make the tree conversion efficient:


<ul>
<li key="2015">Duke</li>
<li key="2016">Villanova</li>
</ul>

<ul>
<li key="2014">Connecticut</li>
<li key="2015">Duke</li>
<li key="2016">Villanova</li>
</ul>

Now React knows that the element with key '2014' is the new one, and the elements with the keys '2015' and '2016' have just moved.


In practice, finding a key is usually not hard. The element you are going to display may already have a unique ID, so the key can just come from your data:


<li key={item.id}>{item.name}</li>

When that’s not the case, you can add a new ID property to your model or hash some parts of the content to generate a key. The key only has to be unique among its siblings, not globally unique.


As a last resort, you can pass an item’s index in the array as a key. This can work well if the items are never reordered, but reorders will be slow.


Reorders can also cause issues with component state when indexes are used as keys. Component instances are updated and reused based on their key. If the key is an index, moving an item changes it. As a result, component state for things like uncontrolled inputs can get mixed up and updated in unexpected ways.


Here is an example of the issues that can be caused by using indexes as keys on CodePen, and here is an updated version of the same example showing how not using indexes as keys will fix these reordering, sorting, and prepending issues.


Tradeoffs


It is important to remember that the reconciliation algorithm is an implementation detail. React could rerender the whole app on every action; the end result would be the same. Just to be clear, rerender in this context means calling render for all components, it doesn’t mean React will unmount and remount them. It will only apply the differences following the rules stated in the previous sections.


We are regularly refining the heuristics in order to make common use cases faster. In the current implementation, you can express the fact that a subtree has been moved amongst its siblings, but you cannot tell that it has moved somewhere else. The algorithm will rerender that full subtree.


Because React relies on heuristics, if the assumptions behind them are not met, performance will suffer.



  1. The algorithm will not try to match subtrees of different component types. If you see yourself alternating between two component types with very similar output, you may want to make it the same type. In practice, we haven’t found this to be an issue.

  2. Keys should be stable, predictable, and unique. Unstable keys (like those produced by Math.random() ) will cause many component instances and DOM nodes to be unnecessarily recreated, which can cause performance degradation and lost state in child components.

Is this page useful? Edit this page
Read article
Refs and the DOM – React

Refs and the DOM

Refs provide a way to access DOM nodes or React elements created in the render method.


In the typical React dataflow, props are the only way that parent components interact with their children. To modify a child, you re-render it with new props. However, there are a few cases where you need to imperatively modify a child outside of the typical dataflow. The child to be modified could be an instance of a React component, or it could be a DOM element. For both of these cases, React provides an escape hatch.


When to Use Refs


There are a few good use cases for refs:



  • Managing focus, text selection, or media playback.

  • Triggering imperative animations.

  • Integrating with third-party DOM libraries.


Avoid using refs for anything that can be done declaratively.


For example, instead of exposing open() and close() methods on a Dialog component, pass an isOpen prop to it.


Don’t Overuse Refs


Your first inclination may be to use refs to “make things happen” in your app. If this is the case, take a moment and think more critically about where state should be owned in the component hierarchy. Often, it becomes clear that the proper place to “own” that state is at a higher level in the hierarchy. See the Lifting State Up guide for examples of this.



Note


The examples below have been updated to use the React.createRef() API introduced in React 16.3. If you are using an earlier release of React, we recommend using callback refs instead.



Creating Refs


Refs are created using React.createRef() and attached to React elements via the ref attribute. Refs are commonly assigned to an instance property when a component is constructed so they can be referenced throughout the component.


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

Accessing Refs


When a ref is passed to an element in render , a reference to the node becomes accessible at the current attribute of the ref.


const node = this.myRef.current;

The value of the ref differs depending on the type of the node:



  • When the ref attribute is used on an HTML element, the ref created in the constructor with React.createRef() receives the underlying DOM element as its current property.

  • When the ref attribute is used on a custom class component, the ref object receives the mounted instance of the component as its current .

  • You may not use the ref attribute on function components because they don’t have instances.


The examples below demonstrate the differences.


Adding a Ref to a DOM Element


This code uses a ref to store a reference to a DOM node:


class CustomTextInput extends React.Component {
constructor(props) {
super(props);
// create a ref to store the textInput DOM element
this.textInput = React.createRef(); this.focusTextInput = this.focusTextInput.bind(this);
}

focusTextInput() {
// Explicitly focus the text input using the raw DOM API
// Note: we're accessing "current" to get the DOM node
this.textInput.current.focus(); }

render() {
// tell React that we want to associate the <input> ref
// with the `textInput` that we created in the constructor
return (
<div>
<input
type="text"
ref={this.textInput} />
<input
type="button"
value="Focus the text input"
onClick={this.focusTextInput}
/>

</div>
);
}
}

React will assign the current property with the DOM element when the component mounts, and assign it back to null when it unmounts. ref updates happen before componentDidMount or componentDidUpdate lifecycle methods.


Adding a Ref to a Class Component


If we wanted to wrap the CustomTextInput above to simulate it being clicked immediately after mounting, we could use a ref to get access to the custom input and call its focusTextInput method manually:


class AutoFocusTextInput extends React.Component {
constructor(props) {
super(props);
this.textInput = React.createRef(); }

componentDidMount() {
this.textInput.current.focusTextInput(); }

render() {
return (
<CustomTextInput ref={this.textInput} /> );
}
}

Note that this only works if CustomTextInput is declared as a class:


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

Refs and Function Components


By default, you may not use the ref attribute on function components because they don’t have instances:


function MyFunctionComponent() {  return <input />;
}

class Parent extends React.Component {
constructor(props) {
super(props);
this.textInput = React.createRef(); }
render() {
// This will *not* work!
return (
<MyFunctionComponent ref={this.textInput} /> );
}
}

If you want to allow people to take a ref to your function component, you can use forwardRef (possibly in conjunction with useImperativeHandle ), or you can convert the component to a class.


You can, however, use the ref attribute inside a function component as long as you refer to a DOM element or a class component:


function CustomTextInput(props) {
// textInput must be declared here so the ref can refer to it const textInput = useRef(null);
function handleClick() {
textInput.current.focus(); }

return (
<div>
<input
type="text"
ref={textInput} />
<input
type="button"
value="Focus the text input"
onClick={handleClick}
/>

</div>
);
}

Exposing DOM Refs to Parent Components


In rare cases, you might want to have access to a child’s DOM node from a parent component. This is generally not recommended because it breaks component encapsulation, but it can occasionally be useful for triggering focus or measuring the size or position of a child DOM node.


While you could add a ref to the child component, this is not an ideal solution, as you would only get a component instance rather than a DOM node. Additionally, this wouldn’t work with function components.


If you use React 16.3 or higher, we recommend to use ref forwarding for these cases. Ref forwarding lets components opt into exposing any child component’s ref as their own . You can find a detailed example of how to expose a child’s DOM node to a parent component in the ref forwarding documentation.


If you use React 16.2 or lower, or if you need more flexibility than provided by ref forwarding, you can use this alternative approach and explicitly pass a ref as a differently named prop.


When possible, we advise against exposing DOM nodes, but it can be a useful escape hatch. Note that this approach requires you to add some code to the child component. If you have absolutely no control over the child component implementation, your last option is to use findDOMNode() , but it is discouraged and deprecated in StrictMode .


Callback Refs


React also supports another way to set refs called “callback refs”, which gives more fine-grain control over when refs are set and unset.


Instead of passing a ref attribute created by createRef() , you pass a function. The function receives the React component instance or HTML DOM element as its argument, which can be stored and accessed elsewhere.


The example below implements a common pattern: using the ref callback to store a reference to a DOM node in an instance property.


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

this.textInput = null;
this.setTextInputRef = element => { this.textInput = element; };
this.focusTextInput = () => { // Focus the text input using the raw DOM API if (this.textInput) this.textInput.focus(); }; }

componentDidMount() {
// autofocus the input on mount
this.focusTextInput(); }

render() {
// Use the `ref` callback to store a reference to the text input DOM
// element in an instance field (for example, this.textInput).
return (
<div>
<input
type="text"
ref={this.setTextInputRef} />

<input
type="button"
value="Focus the text input"
onClick={this.focusTextInput} />

</div>
);
}
}

React will call the ref callback with the DOM element when the component mounts, and call it with null when it unmounts. Refs are guaranteed to be up-to-date before componentDidMount or componentDidUpdate fires.


You can pass callback refs between components like you can with object refs that were created with React.createRef() .


function CustomTextInput(props) {
return (
<div>
<input ref={props.inputRef} /> </div>
);
}

class Parent extends React.Component {
render() {
return (
<CustomTextInput
inputRef={el => this.inputElement = el} />

);
}
}

In the example above, Parent passes its ref callback as an inputRef prop to the CustomTextInput , and the CustomTextInput passes the same function as a special ref attribute to the <input> . As a result, this.inputElement in Parent will be set to the DOM node corresponding to the <input> element in the CustomTextInput .


Legacy API: String Refs


If you worked with React before, you might be familiar with an older API where the ref attribute is a string, like "textInput" , and the DOM node is accessed as this.refs.textInput . We advise against it because string refs have some issues, are considered legacy, and are likely to be removed in one of the future releases .



Note


If you’re currently using this.refs.textInput to access refs, we recommend using either the callback pattern or the createRef API instead.



Caveats with callback refs


If the ref callback is defined as an inline function, it will get called twice during updates, first with null and then again with the DOM element. This is because a new instance of the function is created with each render, so React needs to clear the old ref and set up the new one. You can avoid this by defining the ref callback as a bound method on the class, but note that it shouldn’t matter in most cases.

Is this page useful? Edit this page
Read article
Render Props – React

Render Props

The term “render prop” refers to a technique for sharing code between React components using a prop whose value is a function.


A component with a render prop takes a function that returns a React element and calls it instead of implementing its own render logic.


<DataProvider render={data => (
<h1>Hello {data.target}</h1>
)}
/>

Libraries that use render props include React Router, Downshift and Formik.


In this document, we’ll discuss why render props are useful, and how to write your own.


Use Render Props for Cross-Cutting Concerns


Components are the primary unit of code reuse in React, but it’s not always obvious how to share the state or behavior that one component encapsulates to other components that need that same state.


For example, the following component tracks the mouse position in a web app:


class MouseTracker extends React.Component {
constructor(props) {
super(props);
this.handleMouseMove = this.handleMouseMove.bind(this);
this.state = { x: 0, y: 0 };
}

handleMouseMove(event) {
this.setState({
x: event.clientX,
y: event.clientY
});
}

render() {
return (
<div style={{ height: '100vh' }} onMouseMove={this.handleMouseMove}>
<h1>Move the mouse around!</h1>
<p>The current mouse position is ({this.state.x}, {this.state.y})</p>
</div>
);
}
}

As the cursor moves around the screen, the component displays its (x, y) coordinates in a <p> .


Now the question is: How can we reuse this behavior in another component? In other words, if another component needs to know about the cursor position, can we encapsulate that behavior so that we can easily share it with that component?


Since components are the basic unit of code reuse in React, let’s try refactoring the code a bit to use a <Mouse> component that encapsulates the behavior we need to reuse elsewhere.


// The <Mouse> component encapsulates the behavior we need...
class Mouse extends React.Component {
constructor(props) {
super(props);
this.handleMouseMove = this.handleMouseMove.bind(this);
this.state = { x: 0, y: 0 };
}

handleMouseMove(event) {
this.setState({
x: event.clientX,
y: event.clientY
});
}

render() {
return (
<div style={{ height: '100vh' }} onMouseMove={this.handleMouseMove}>

{/* ...but how do we render something other than a <p>? */}
<p>The current mouse position is ({this.state.x}, {this.state.y})</p>
</div>
);
}
}

class MouseTracker extends React.Component {
render() {
return (
<>
<h1>Move the mouse around!</h1>
<Mouse />
</>
);
}
}

Now the <Mouse> component encapsulates all behavior associated with listening for mousemove events and storing the (x, y) position of the cursor, but it’s not yet truly reusable.


For example, let’s say we have a <Cat> component that renders the image of a cat chasing the mouse around the screen. We might use a <Cat mouse={{ x, y }}> prop to tell the component the coordinates of the mouse so it knows where to position the image on the screen.


As a first pass, you might try rendering the <Cat> inside <Mouse> ’s render method , like this:


class Cat extends React.Component {
render() {
const mouse = this.props.mouse;
return (
<img src="/cat.jpg" style={{ position: 'absolute', left: mouse.x, top: mouse.y }} />
);
}
}

class MouseWithCat extends React.Component {
constructor(props) {
super(props);
this.handleMouseMove = this.handleMouseMove.bind(this);
this.state = { x: 0, y: 0 };
}

handleMouseMove(event) {
this.setState({
x: event.clientX,
y: event.clientY
});
}

render() {
return (
<div style={{ height: '100vh' }} onMouseMove={this.handleMouseMove}>

{/*
We could just swap out the <p> for a <Cat> here ... but then
we would need to create a separate <MouseWithSomethingElse>
component every time we need to use it, so <MouseWithCat>
isn't really reusable yet.
*/
}
<Cat mouse={this.state} />
</div>
);
}
}

class MouseTracker extends React.Component {
render() {
return (
<div>
<h1>Move the mouse around!</h1>
<MouseWithCat />
</div>
);
}
}

This approach will work for our specific use case, but we haven’t achieved the objective of truly encapsulating the behavior in a reusable way. Now, every time we want the mouse position for a different use case, we have to create a new component (i.e. essentially another <MouseWithCat> ) that renders something specifically for that use case.


Here’s where the render prop comes in: Instead of hard-coding a <Cat> inside a <Mouse> component, and effectively changing its rendered output, we can provide <Mouse> with a function prop that it uses to dynamically determine what to render–a render prop.


class Cat extends React.Component {
render() {
const mouse = this.props.mouse;
return (
<img src="/cat.jpg" style={{ position: 'absolute', left: mouse.x, top: mouse.y }} />
);
}
}

class Mouse extends React.Component {
constructor(props) {
super(props);
this.handleMouseMove = this.handleMouseMove.bind(this);
this.state = { x: 0, y: 0 };
}

handleMouseMove(event) {
this.setState({
x: event.clientX,
y: event.clientY
});
}

render() {
return (
<div style={{ height: '100vh' }} onMouseMove={this.handleMouseMove}>

{/*
Instead of providing a static representation of what <Mouse> renders,
use the `render` prop to dynamically determine what to render.
*/
}
{this.props.render(this.state)}
</div>
);
}
}

class MouseTracker extends React.Component {
render() {
return (
<div>
<h1>Move the mouse around!</h1>
<Mouse render={mouse => (
<Cat mouse={mouse} />
)}
/>

</div>
);
}
}

Now, instead of effectively cloning the <Mouse> component and hard-coding something else in its render method to solve for a specific use case, we provide a render prop that <Mouse> can use to dynamically determine what it renders.


More concretely, a render prop is a function prop that a component uses to know what to render.


This technique makes the behavior that we need to share extremely portable. To get that behavior, render a <Mouse> with a render prop that tells it what to render with the current (x, y) of the cursor.


One interesting thing to note about render props is that you can implement most higher-order components (HOC) using a regular component with a render prop. For example, if you would prefer to have a withMouse HOC instead of a <Mouse> component, you could easily create one using a regular <Mouse> with a render prop:


// If you really want a HOC for some reason, you can easily
// create one using a regular component with a render prop!
function withMouse(Component) {
return class extends React.Component {
render() {
return (
<Mouse render={mouse => (
<Component {...this.props} mouse={mouse} />
)}
/>

);
}
}
}

So using a render prop makes it possible to use either pattern.


Using Props Other Than render


It’s important to remember that just because the pattern is called “render props” you don’t have to use a prop named render to use this pattern . In fact, any prop that is a function that a component uses to know what to render is technically a “render prop”.


Although the examples above use render , we could just as easily use the children prop!


<Mouse children={mouse => (
<p>The mouse position is {mouse.x}, {mouse.y}</p>
)}
/>

And remember, the children prop doesn’t actually need to be named in the list of “attributes” in your JSX element. Instead, you can put it directly inside the element!


<Mouse>
{mouse => (
<p>The mouse position is {mouse.x}, {mouse.y}</p>
)}
</Mouse>

You’ll see this technique used in the react-motion API.


Since this technique is a little unusual, you’ll probably want to explicitly state that children should be a function in your propTypes when designing an API like this.


Mouse.propTypes = {
children: PropTypes.func.isRequired
};

Caveats


Be careful when using Render Props with React.PureComponent


Using a render prop can negate the advantage that comes from using React.PureComponent if you create the function inside a render method. This is because the shallow prop comparison will always return false for new props, and each render in this case will generate a new value for the render prop.


For example, continuing with our <Mouse> component from above, if Mouse were to extend React.PureComponent instead of React.Component , our example would look like this:


class Mouse extends React.PureComponent {
// Same implementation as above...
}

class MouseTracker extends React.Component {
render() {
return (
<div>
<h1>Move the mouse around!</h1>

{/*
This is bad! The value of the `render` prop will
be different on each render.
*/
}
<Mouse render={mouse => (
<Cat mouse={mouse} />
)}
/>

</div>
);
}
}

In this example, each time <MouseTracker> renders, it generates a new function as the value of the <Mouse render> prop, thus negating the effect of <Mouse> extending React.PureComponent in the first place!


To get around this problem, you can sometimes define the prop as an instance method, like so:


class MouseTracker extends React.Component {
// Defined as an instance method, `this.renderTheCat` always
// refers to *same* function when we use it in render
renderTheCat(mouse) {
return <Cat mouse={mouse} />;
}

render() {
return (
<div>
<h1>Move the mouse around!</h1>
<Mouse render={this.renderTheCat} />
</div>
);
}
}

In cases where you cannot define the prop statically (e.g. because you need to close over the component’s props and/or state) <Mouse> should extend React.Component instead.

Is this page useful? Edit this page
Read article
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
Read article
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