React is an open-source front-end JavaScript library that is used for building user interfaces, especially for single-page applications. It is used for handling view layer for web and mobile apps. React was created by Jordan Walke, a software engineer working for Facebook. React was first deployed on Facebook's News Feed in 2011 and on Instagram in 2012.
The major features of React are:
JSX is a XML-like syntax extension to ECMAScript (the acronym stands for JavaScript XML). Basically it just provides syntactic sugar for the React.createElement()
function, giving us expressiveness of JavaScript along with HTML like template syntax.
In the example below text inside <h1>
tag is returned as JavaScript function to the render function.
class App extends React.Component {
render() {
return(
<div>
<h1>{'Welcome to React world!'}</h1>
</div>
)
}
}
An Element is a plain object describing what you want to appear on the screen in terms of the DOM nodes or other components. Elements can contain other Elements in their props. Creating a React element is cheap. Once an element is created, it is never mutated.
The object representation of React Element would be as follows:
const element = React.createElement(
'div',
{id: 'login-btn'},
'Login'
)
The above React.createElement()
function returns an object:
{
type: 'div',
props: {
children: 'Login',
id: 'login-btn'
}
}
And finally it renders to the DOM using ReactDOM.render()
:
<div id='login-btn'>Login</div>
Whereas a Component can be declared in several different ways. It can be a class with a render()
method or it can be defined as a function. In either case, it takes props as an input, and returns a JSX tree as the output:
const Button = ({ onLogin }) =>
<div id={'login-btn'} onClick={onLogin}>Login</div>
Then JSX gets transpiled to a React.createElement()
function tree:
const Button = ({ onLogin }) => React.createElement(
'div',
{ id: 'login-btn', onClick: onLogin },
'Login'
)
There are two possible ways to create a component.
function Greeting({ message }) {
return <h1>{`Hello, ${message}`}</h1>
}
class Greeting extends React.Component {
render() {
return <h1>{`Hello, ${this.props.message}`}</h1>
}
}
If the component needs state or lifecycle methods then use class component otherwise use function component. However, from React 16.8 with the addition of Hooks, you could use state, lifecycle methods and other features that were only available in class component right in your function component. *So, it is always recommended to use Function components, unless you need a React functionality whose Function component equivalent is not present yet, like Error Boundaries *
React.PureComponent
is exactly the same as React.Component
except that it handles the shouldComponentUpdate()
method for you. When props or state changes, PureComponent will do a shallow comparison on both props and state. Component on the other hand won't compare current props and state to next out of the box. Thus, the component will re-render by default whenever shouldComponentUpdate
is called.
State of a component is an object that holds some information that may change over the lifetime of the component. We should always try to make our state as simple as possible and minimize the number of stateful components.
Let's create a user component with message state:
class User extends React.Component {
constructor(props) {
super(props)
this.state = {
message: 'Welcome to React world'
}
}
render() {
return (
<div>
<h1>{this.state.message}</h1>
</div>
)
}
}
State is similar to props, but it is private and fully controlled by the component ,i.e., it is not accessible to any other component till the owner component decides to pass it.
Props are inputs to components. They are single values or objects containing a set of values that are passed to components on creation using a naming convention similar to HTML-tag attributes. They are data passed down from a parent component to a child component.
The primary purpose of props in React is to provide following component functionality:
this.props.reactProp
inside component's render()
method.For example, let us create an element with reactProp
property:
<Element reactProp={'1'} />
This reactProp
(or whatever you came up with) name then becomes a property attached to React's native props object which originally already exists on all components created using React library.
props.reactProp
Both props and state are plain JavaScript objects. While both of them hold information that influences the output of render, they are different in their functionality with respect to component. Props get passed to the component similar to function parameters whereas state is managed within the component similar to variables declared within a function.
If you try to update the state directly then it won't re-render the component.
//Wrong
this.state.message = 'Hello world'
Instead use setState()
method. It schedules an update to a component's state object. When state changes, the component responds by re-rendering.
//Correct
this.setState({ message: 'Hello World' })
Note: You can directly assign to the state object either in constructor or using latest javascript's class field declaration syntax.
The callback function is invoked when setState finished and the component gets rendered. Since setState()
is asynchronous the callback function is used for any post action.
Note: It is recommended to use lifecycle method rather than this callback function.
setState({ name: 'John' }, () => console.log('The name has updated and component re-rendered'))
Below are some of the main differences between HTML and React event handling,
<button onclick='activateLasers()'>
Whereas in React it follows camelCase convention:
<button onClick={activateLasers}>
false
to prevent default behavior:<a href='#' onclick='console.log("The link was clicked."); return false;' />
Whereas in React you must call preventDefault()
explicitly:
function handleClick(event) {
event.preventDefault()
console.log('The link was clicked.')
}
()
Whereas in react you should not append ()
with the function name. (refer "activateLasers" function in the first point for example)There are 3 possible ways to achieve this:
class Foo extends Component {
constructor(props) {
super(props);
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
console.log('Click happened');
}
render() {
return <button onClick={this.handleClick}>Click Me</button>;
}
}
handleClick = () => {
console.log('this is:', this)
}
<button onClick={this.handleClick}>
{'Click me'}
</button>
handleClick() {
console.log('Click happened');
}
render() {
return <button onClick={() => this.handleClick()}>Click Me</button>;
}
Note: If the callback is passed as prop to child components, those components might do an extra re-rendering. In those cases, it is preferred to go with .bind()
or public class fields syntax approach considering performance.
You can use an arrow function to wrap around an event handler and pass parameters:
<button onClick={() => this.handleClick(id)} />
This is an equivalent to calling .bind
:
<button onClick={this.handleClick.bind(this, id)} />
Apart from these two approaches, you can also pass arguments to a function which is defined as arrow function
<button onClick={this.handleClick(id)} />
handleClick = (id) => () => {
console.log("Hello, your ticket number is", id)
};
SyntheticEvent
is a cross-browser wrapper around the browser's native event. Its API is same as the browser's native event, including stopPropagation()
and preventDefault()
, except the events work identically across all browsers.
You can use either if statements or ternary expressions which are available from JS to conditionally render expressions. Apart from these approaches, you can also embed any expressions in JSX by wrapping them in curly braces and then followed by JS logical operator &&
.
<h1>Hello!</h1>
{
messages.length > 0 && !isLogin?
<h2>
You have {messages.length} unread messages.
</h2>
:
<h2>
You don't have unread messages.
</h2>
}
A key
is a special string attribute you should include when creating arrays of elements. Key prop helps React identify which items have changed, are added, or are removed.
Most often we use ID from our data as key:
const todoItems = todos.map((todo) =>
<li key={todo.id}>
{todo.text}
</li>
)
When you don't have stable IDs for rendered items, you may use the item index as a key as a last resort:
const todoItems = todos.map((todo, index) =>
<li key={index}>
{todo.text}
</li>
)
Note:
li
tag.key
prop is not present on list items.The ref is used to return a reference to the element. They should be avoided in most cases, however, they can be useful when you need a direct access to the DOM element or an instance of a component.
There are two approaches:
React.createRef()
method and attached to React elements via the ref
attribute. In order to use refs throughout the component, just assign the ref to the instance property within constructor.class MyComponent extends React.Component {
constructor(props) {
super(props)
this.myRef = React.createRef()
}
render() {
return <div ref={this.myRef} />
}
}
class SearchBar extends Component {
constructor(props) {
super(props);
this.txtSearch = null;
this.state = { term: '' };
this.setInputSearchRef = e => {
this.txtSearch = e;
}
}
onInputChange(event) {
this.setState({ term: this.txtSearch.value });
}
render() {
return (
<input
value={this.state.term}
onChange={this.onInputChange.bind(this)}
ref={this.setInputSearchRef} />
);
}
}
You can also use refs in function components using closures. Note: You can also use inline ref callbacks even though it is not a recommended approach.
Ref forwarding is a feature that lets some components take a ref they receive, and pass it further down to a child.
const ButtonElement = React.forwardRef((props, ref) => (
<button ref={ref} className="CustomButton">
{props.children}
</button>
));
// Create ref to the DOM button:
const ref = React.createRef();
<ButtonElement ref={ref}>{'Forward Ref'}</ButtonElement>
It is preferred to use callback refs over findDOMNode()
API. Because findDOMNode()
prevents certain improvements in React in the future.
The legacy approach of using findDOMNode
:
class MyComponent extends Component {
componentDidMount() {
findDOMNode(this).scrollIntoView()
}
render() {
return <div />
}
}
The recommended approach is:
class MyComponent extends Component {
constructor(props){
super(props);
this.node = createRef();
}
componentDidMount() {
this.node.current.scrollIntoView();
}
render() {
return <div ref={this.node} />
}
}
If you worked with React before, you might be familiar with an older API where the ref
attribute is a string, like ref={'textInput'}
, and the DOM node is accessed as this.refs.textInput
. We advise against it because string refs have below issues, and are considered legacy. String refs were removed in React v16.
this.refs
, as well as its type (which could be different). Callback refs are friendlier to static analysis.(e.g.DataGrid renderRow=)
class MyComponent extends Component {
renderRow = (index) => {
// This won't work. Ref will get attached to DataTable rather than MyComponent:
return <input ref={'input-' + index} />;
// This would work though! Callback refs are awesome.
return <input ref={input => this['input-' + index] = input} />;
}
render() {
return <DataTable data={this.props.data} renderRow={this.renderRow} />
}
}
The Virtual DOM (VDOM) is an in-memory representation of Real DOM. The representation of a UI is kept in memory and synced with the "real" DOM. It's a step that happens between the render function being called and the displaying of elements on the screen. This entire process is called reconciliation.
The Virtual DOM works in three simple steps:
1- Whenever any underlying data changes, the entire UI is re-rendered in Virtual DOM representation.
2- Then the difference between the previous DOM representation and the new one is calculated.
3- Once the calculations are done, the real DOM will be updated with only the things that have actually changed.
The Shadow DOM is a browser technology designed primarily for scoping variables and CSS in web components. The Virtual DOM is a concept implemented by libraries in JavaScript on top of browser APIs.
Fiber is the new reconciliation engine or reimplementation of core algorithm in React v16. The goal of React Fiber is to increase its suitability for areas like animation, layout, gestures, ability to pause, abort, or reuse work and assign priority to different types of updates; and new concurrency primitives.
The goal of React Fiber is to increase its suitability for areas like animation, layout, and gestures. Its headline feature is incremental rendering: the ability to split rendering work into chunks and spread it out over multiple frames.
From documentation
Its main goals are:
A component that controls the input elements within the forms on subsequent user input is called Controlled Component, i.e, every state mutation will have an associated handler function.
For example, to write all the names in uppercase letters, we use handleChange as below,
handleChange(event) {
this.setState({value: event.target.value.toUpperCase()})
}
The Uncontrolled Components are the ones that store their own state internally, and you query the DOM using a ref to find its current value when you need it. This is a bit more like traditional HTML.
In the below UserProfile component, the name
input is accessed using ref.
class UserProfile 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>
);
}
}
In most cases, it's recommend to use 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.
JSX elements will be transpiled to React.createElement()
functions to create React elements which are going to be used for the object representation of UI. Whereas cloneElement
is used to clone an element and pass it new props.
When several components need to share the same changing data then it is recommended to lift the shared state up to their closest common ancestor. That means if two child components share the same data from its parent, then move the state to parent instead of maintaining local state in both of the child components.
The component lifecycle has three distinct lifecycle phases:
Mounting: The component is ready to mount in the browser DOM. This phase covers initialization from constructor()
, getDerivedStateFromProps()
, render()
, and componentDidMount()
lifecycle methods.
Updating: In this phase, the component gets updated in two ways, sending the new props and updating the state either from setState()
or forceUpdate()
. This phase covers getDerivedStateFromProps()
, shouldComponentUpdate()
, render()
, getSnapshotBeforeUpdate()
and componentDidUpdate()
lifecycle methods.
Unmounting: In this last phase, the component is not needed and gets unmounted from the browser DOM. This phase includes componentWillUnmount()
lifecycle method.
It's worth mentioning that React internally has a concept of phases when applying changes to the DOM. They are separated as follows
Render The component will render without any side effects. This applies to Pure components and in this phase, React can pause, abort, or restart the render.
Pre-commit Before the component actually applies the changes to the DOM, there is a moment that allows React to read from the DOM through the getSnapshotBeforeUpdate()
.
Commit React works with the DOM and executes the final lifecycles respectively componentDidMount()
for mounting, componentDidUpdate()
for updating, and componentWillUnmount()
for unmounting.
React 16.3+ Phases (or an interactive version)
Before React 16.3
Before React 16.3true
. If you are sure that the component doesn't need to render after state or props are updated, you can return false value. It is a great place to improve performance as it allows you to prevent a re-render if component receives new prop.shouldComponentUpdate()
which returns true.render()
and is invoked on every render. This exists for rare use cases where you need a derived state. Worth reading if you need derived state.true
. If you are sure that the component doesn't need to render after the state or props are updated, you can return a false value. It is a great place to improve performance as it allows you to prevent a re-render if component receives a new prop.componentDidUpdate()
. This is useful to capture information from the DOM i.e. scroll position.shouldComponentUpdate()
returns false
.A higher-order component (HOC) is a function that takes a component and returns a new component. Basically, it's a pattern that is derived from React's compositional nature.
We call them pure components because they can accept any dynamically provided child component but they won't modify or copy any behavior from their input components.
const EnhancedComponent = higherOrderComponent(WrappedComponent)
HOC can be used for many use cases:
You can add/edit props passed to the component using props proxy pattern like this:
function HOC(WrappedComponent) {
return class Test extends Component {
render() {
const newProps = {
title: 'New Header',
footer: false,
showFeatureX: false,
showFeatureY: true
}
return <WrappedComponent {...this.props} {...newProps} />
}
}
}
Context provides a way to pass data through the component tree without having to pass props down manually at every level.
For example, authenticated users, locale preferences, UI themes need to be accessed in the application by many components.
const {Provider, Consumer} = React.createContext(defaultValue)
Children is a prop (this.props.children
) that allows you to pass components as data to other components, just like any other prop you use. Component tree put between component's opening and closing tag will be passed to that component as children
prop.
There are several methods available in the React API to work with this prop. These include React.Children.map
, React.Children.forEach
, React.Children.count
, React.Children.only
, React.Children.toArray
.
A simple usage of children prop looks as below,
const MyDiv = React.createClass({
render: function() {
return <div>{this.props.children}</div>
}
})
ReactDOM.render(
<MyDiv>
<span>{'Hello'}</span>
<span>{'World'}</span>
</MyDiv>,
node
)
The comments in React/JSX are similar to JavaScript Multiline comments but are wrapped in curly braces.
Single-line comments:
<div>
{/* Single-line comments(In vanilla JavaScript, the single-line comments are represented by double slash(//)) */}
{`Welcome ${user}, let's play React`}
</div>
Multi-line comments:
<div>
{/* Multi-line comments for more than
one line */}
{`Welcome ${user}, let's play React`}
</div>
A child class constructor cannot make use of this
reference until the super()
method has been called. The same applies to ES6 sub-classes as well. The main reason for passing props parameter to super()
call is to access this.props
in your child constructors.
Passing props:
class MyComponent extends React.Component {
constructor(props) {
super(props)
console.log(this.props) // prints { name: 'John', age: 42 }
}
}
Not passing props:
class MyComponent extends React.Component {
constructor(props) {
super()
console.log(this.props) // prints undefined
// but props parameter is still available
console.log(props) // prints { name: 'John', age: 42 }
}
render() {
// no difference outside constructor
console.log(this.props) // prints { name: 'John', age: 42 }
}
}
The above code snippets reveals that this.props
is different only within the constructor. It would be the same outside the constructor.
When a component's props or state change, React decides whether an actual DOM update is necessary by comparing the newly returned element with the previously rendered one. When they are not equal, React will update the DOM. This process is called reconciliation.
If you are using ES6 or the Babel transpiler to transform your JSX code then you can accomplish this with computed property names.
handleInputChange(event) {
this.setState({ [event.target.id]: event.target.value })
}
You need to make sure that function is not being called while passing the function as a parameter.
render() {
// Wrong: handleClick is called instead of passed as a reference!
return <button onClick={this.handleClick()}>{'Click Me'}</button>
}
Instead, pass the function itself without parenthesis:
render() {
// Correct: handleClick is passed as a reference!
return <button onClick={this.handleClick}>{'Click Me'}</button>
}
No, currently React.lazy
function supports default exports only. If you would like to import modules which are named exports, you can create an intermediate module that reexports it as the default. It also ensures that tree shaking keeps working and don’t pull unused components.
Let's take a component file which exports multiple named components,
// MoreComponents.js
export const SomeComponent = /* ... */;
export const UnusedComponent = /* ... */;
and reexport MoreComponents.js
components in an intermediate file IntermediateComponent.js
// IntermediateComponent.js
export { SomeComponent as default } from "./MoreComponents.js";
Now you can import the module using lazy function as below,
import React, { lazy } from 'react';
const SomeComponent = lazy(() => import("./IntermediateComponent.js"));
class
is a keyword in JavaScript, and JSX is an extension of JavaScript. That's the principal reason why React uses className
instead of class
. Pass a string as the className
prop.
render() {
return <span className={'menu navigation-menu'}>{'Menu'}</span>
}
It's a common pattern in React which is used for a component to return multiple elements. Fragments let you group a list of children without adding extra nodes to the DOM.
render() {
return (
<React.Fragment>
<ChildA />
<ChildB />
<ChildC />
</React.Fragment>
)
}
There is also a shorter syntax, but it's not supported in many tools:
render() {
return (
<>
<ChildA />
<ChildB />
<ChildC />
</>
)
}
Below are the list of reasons,
Portal is a recommended way to render children into a DOM node that exists outside the DOM hierarchy of the parent component.
ReactDOM.createPortal(child, container)
The first argument is any render-able React child, such as an element, string, or fragment. The second argument is a DOM element.
If the behaviour of a component is independent of its state then it can be a stateless component. You can use either a function or a class for creating stateless components. But unless you need to use a lifecycle hook in your components, you should go for function components. There are a lot of benefits if you decide to use function components here; they are easy to write, understand, and test, a little faster, and you can avoid the this
keyword altogether.
If the behaviour of a component is dependent on the state of the component then it can be termed as stateful component. These stateful components are always class components and have a state that gets initialized in the constructor
.
class App extends Component {
constructor(props) {
super(props)
this.state = { count: 0 }
}
render() {
// ...
}
}
React 16.8 Update:
Hooks let you use state and other React features without writing classes.
The Equivalent Functional Component
import React, {useState} from 'react';
const App = (props) => {
const [count, setCount] = useState(0);
return (
// JSX
)
}
When the application is running in development mode, React will automatically check all props that we set on components to make sure they have correct type. If the type is incorrect, React will generate warning messages in the console. It's disabled in production mode due to performance impact. The mandatory props are defined with isRequired
.
The set of predefined prop types:
PropTypes.number
PropTypes.string
PropTypes.array
PropTypes.object
PropTypes.func
PropTypes.node
PropTypes.element
PropTypes.bool
PropTypes.symbol
PropTypes.any
We can define propTypes
for User
component as below:
import React from 'react'
import PropTypes from 'prop-types'
class User extends React.Component {
static propTypes = {
name: PropTypes.string.isRequired,
age: PropTypes.number.isRequired
}
render() {
return (
<>
<h1>{`Welcome, ${this.props.name}`}</h1>
<h2>{`Age, ${this.props.age}`}</h2>
</>
)
}
}
Note: In React v15.5 PropTypes were moved from React.PropTypes
to prop-types
library.
The Equivalent Functional Component
import React from 'react'
import PropTypes from 'prop-types'
function User({name, age}) {
return (
<>
<h1>{`Welcome, ${name}`}</h1>
<h2>{`Age, ${age}`}</h2>
</>
)
}
User.propTypes = {
name: PropTypes.string.isRequired,
age: PropTypes.number.isRequired
}
Below are the list of main advantages of React,
Apart from the advantages, there are few limitations of React too,
Error boundaries are components that catch JavaScript errors anywhere in their child component tree, log those errors, and display a fallback UI instead of the component tree that crashed.
A class component becomes an error boundary if it defines a new lifecycle method called componentDidCatch(error, info)
or static getDerivedStateFromError()
:
class ErrorBoundary extends React.Component {
constructor(props) {
super(props)
this.state = { hasError: false }
}
componentDidCatch(error, info) {
// You can also log the error to an error reporting service
logErrorToMyService(error, info)
}
static getDerivedStateFromError(error) {
// Update state so the next render will show the fallback UI.
return { hasError: true };
}
render() {
if (this.state.hasError) {
// You can render any custom fallback UI
return <h1>{'Something went wrong.'}</h1>
}
return this.props.children
}
}
After that use it as a regular component:
<ErrorBoundary>
<MyWidget />
</ErrorBoundary>
React v15 provided very basic support for error boundaries using unstable_handleError
method. It has been renamed to componentDidCatch
in React v16.
Normally we use PropTypes library (React.PropTypes
moved to a prop-types
package since React v15.5) for type checking in the React applications. For large code bases, it is recommended to use static type checkers such as Flow or TypeScript, that perform type checking at compile time and provide auto-completion features.
The react-dom
package provides DOM-specific methods that can be used at the top level of your app. Most of the components are not required to use this module. Some of the methods of this package are:
render()
hydrate()
unmountComponentAtNode()
findDOMNode()
createPortal()
This method is used to render a React element into the DOM in the supplied container and return a reference to the component. If the React element was previously rendered into container, it will perform an update on it and only mutate the DOM as necessary to reflect the latest changes.
ReactDOM.render(element, container, [callback])
If the optional callback is provided, it will be executed after the component is rendered or updated.
The ReactDOMServer
object enables you to render components to static markup (typically used on node server). This object is mainly used for server-side rendering (SSR). The following methods can be used in both the server and browser environments:
renderToString()
renderToStaticMarkup()
For example, you generally run a Node-based web server like Express, Hapi, or Koa, and you call renderToString
to render your root component to a string, which you then send as response.
// using Express
import { renderToString } from 'react-dom/server'
import MyPage from './MyPage'
app.get('/', (req, res) => {
res.write('<!DOCTYPE html><html><head><title>My Page</title></head><body>')
res.write('<div id="content">')
res.write(renderToString(<MyPage/>))
res.write('</div></body></html>')
res.end()
})
The dangerouslySetInnerHTML
attribute is React's replacement for using innerHTML
in the browser DOM. Just like innerHTML
, it is risky to use this attribute considering cross-site scripting (XSS) attacks. You just need to pass a __html
object as key and HTML text as value.
In this example MyComponent uses dangerouslySetInnerHTML
attribute for setting HTML markup:
function createMarkup() {
return { __html: 'First · Second' }
}
function MyComponent() {
return <div dangerouslySetInnerHTML={createMarkup()} />
}
The style
attribute accepts a JavaScript object with camelCased properties rather than a CSS string. This is consistent with the DOM style JavaScript property, is more efficient, and prevents XSS security holes.
const divStyle = {
color: 'blue',
backgroundImage: 'url(' + imgUrl + ')'
};
function HelloWorldComponent() {
return <div style={divStyle}>Hello World!</div>
}
Style keys are camelCased in order to be consistent with accessing the properties on DOM nodes in JavaScript (e.g. node.style.backgroundImage
).
Handling events in React elements has some syntactic differences:
When you use setState()
, then apart from assigning to the object state React also re-renders the component and all its children. You would get error like this: Can only update a mounted or mounting component. So we need to use this.state
to initialize variables inside constructor.
Keys should be stable, predictable, and unique so that React can keep track of elements.
In the below code snippet each element's key will be based on ordering, rather than tied to the data that is being represented. This limits the optimizations that React can do.
{todos.map((todo, index) =>
<Todo
{...todo}
key={index}
/>
)}
If you use element data for unique key, assuming todo.id is unique to this list and stable, React would be able to reorder elements without needing to reevaluate them as much.
{todos.map((todo) =>
<Todo {...todo}
key={todo.id} />
)}
Yes, it is safe to use setState()
inside componentWillMount()
method. But at the same it is recommended to avoid async initialization in componentWillMount()
lifecycle method. componentWillMount()
is invoked immediately before mounting occurs. It is called before render()
, therefore setting state in this method will not trigger a re-render. Avoid introducing any side-effects or subscriptions in this method. We need to make sure async calls for component initialization happened in componentDidMount()
instead of componentWillMount()
.
componentDidMount() {
axios.get(`api/todos`)
.then((result) => {
this.setState({
messages: [...result.data]
})
})
}
If the props on the component are changed without the component being refreshed, the new prop value will never be displayed because the constructor function will never update the current state of the component. The initialization of state from props only runs when the component is first created.
The below component won't display the updated input value:
class MyComponent extends React.Component {
constructor(props) {
super(props)
this.state = {
records: [],
inputValue: this.props.inputValue
};
}
render() {
return <div>{this.state.inputValue}</div>
}
}
Using props inside render method will update the value:
class MyComponent extends React.Component {
constructor(props) {
super(props)
this.state = {
record: []
}
}
render() {
return <div>{this.props.inputValue}</div>
}
}
In some cases you want to render different components depending on some state. JSX does not render false
or undefined
, so you can use conditional short-circuiting to render a given part of your component only if a certain condition is true.
const MyComponent = ({ name, address }) => (
<div>
<h2>{name}</h2>
{address &&
<p>{address}</p>
}
</div>
)
If you need an if-else
condition then use ternary operator.
const MyComponent = ({ name, address }) => (
<div>
<h2>{name}</h2>
{address
? <p>{address}</p>
: <p>{'Address is not available'}</p>
}
</div>
)
When we spread props we run into the risk of adding unknown HTML attributes, which is a bad practice. Instead we can use prop destructuring with ...rest
operator, so it will add only required props.
For example,
const ComponentA = () =>
<ComponentB isDisplay={true} className={'componentStyle'} />
const ComponentB = ({ isDisplay, ...domProps }) =>
<div {...domProps}>{'ComponentB'}</div>
You can decorate your class components, which is the same as passing the component into a function. Decorators are flexible and readable way of modifying component functionality.
@setTitle('Profile')
class Profile extends React.Component {
//....
}
/*
title is a string that will be set as a document title
WrappedComponent is what our decorator will receive when
put directly above a component class as seen in the example above
*/
const setTitle = (title) => (WrappedComponent) => {
return class extends React.Component {
componentDidMount() {
document.title = title
}
render() {
return <WrappedComponent {...this.props} />
}
}
}
Note: Decorators are a feature that didn't make it into ES7, but are currently a stage 2 proposal.
There are memoize libraries available which can be used on function components.
For example moize
library can memoize the component in another component.
import moize from 'moize'
import Component from './components/Component' // this module exports a non-memoized component
const MemoizedFoo = moize.react(Component)
const Consumer = () => {
<div>
{'I will memoize the following entry:'}
<MemoizedFoo/>
</div>
}
Update: Since React v16.6.0, we have a React.memo
. It provides a higher order component which memoizes component unless the props change. To use it, simply wrap the component using React.memo before you use it.
const MemoComponent = React.memo(function MemoComponent(props) {
/* render using props */
});
OR
export default React.memo(MyFunctionComponent);
React is already equipped to handle rendering on Node servers. A special version of the DOM renderer is available, which follows the same pattern as on the client side.
import ReactDOMServer from 'react-dom/server'
import App from './App'
ReactDOMServer.renderToString(<App />)
This method will output the regular HTML as a string, which can be then placed inside a page body as part of the server response. On the client side, React detects the pre-rendered content and seamlessly picks up where it left off.
You should use Webpack's DefinePlugin
method to set NODE_ENV
to production
, by which it strip out things like propType validation and extra warnings. Apart from this, if you minify the code, for example, Uglify's dead-code elimination to strip out development only code and comments, it will drastically reduce the size of your bundle.
The create-react-app
CLI tool allows you to quickly create & run React applications with no configuration step.
Let's create Todo App using CRA:
# Installation
$ npm install -g create-react-app
# Create new project
$ create-react-app todo-app
$ cd todo-app
# Build, test and run
$ npm run build
$ npm run test
$ npm start
It includes everything we need to build a React app:
The lifecycle methods are called in the following order when an instance of a component is being created and inserted into the DOM.
constructor()
static getDerivedStateFromProps()
render()
componentDidMount()
The following lifecycle methods going to be unsafe coding practices and will be more problematic with async rendering.
componentWillMount()
componentWillReceiveProps()
componentWillUpdate()
Starting with React v16.3 these methods are aliased with UNSAFE_
prefix, and the unprefixed version will be removed in React v17.
The new static getDerivedStateFromProps()
lifecycle method is invoked after a component is instantiated as well as before it is re-rendered. It can return an object to update state, or null
to indicate that the new props do not require any state updates.
class MyComponent extends React.Component {
static getDerivedStateFromProps(props, state) {
// ...
}
}
This lifecycle method along with componentDidUpdate()
covers all the use cases of componentWillReceiveProps()
.
The new getSnapshotBeforeUpdate()
lifecycle method is called right before DOM updates. The return value from this method will be passed as the third parameter to componentDidUpdate()
.
class MyComponent extends React.Component {
getSnapshotBeforeUpdate(prevProps, prevState) {
// ...
}
}
This lifecycle method along with componentDidUpdate()
covers all the use cases of componentWillUpdate()
.
Both render props and higher-order components render only a single child but in most of the cases Hooks are a simpler way to serve this by reducing nesting in your tree.
It is recommended to name the component by reference instead of using displayName
.
Using displayName
for naming component:
export default React.createClass({
displayName: 'TodoApp',
// ...
})
The recommended approach:
export default class TodoApp extends React.Component {
// ...
}
also
const TodoApp = () => {
//...
}
export default TodoApp;
Recommended ordering of methods from mounting to render stage:
static
methodsconstructor()
getChildContext()
componentWillMount()
componentDidMount()
componentWillReceiveProps()
shouldComponentUpdate()
componentWillUpdate()
componentDidUpdate()
componentWillUnmount()
onClickSubmit()
or onChangeDescription()
getSelectReason()
or getFooterContent()
renderNavigation()
or renderProfilePicture()
render()
A switching component is a component that renders one of many components. We need to use object to map prop values to components.
For example, a switching component to display different pages based on page
prop:
import HomePage from './HomePage'
import AboutPage from './AboutPage'
import ServicesPage from './ServicesPage'
import ContactPage from './ContactPage'
const PAGES = {
home: HomePage,
about: AboutPage,
services: ServicesPage,
contact: ContactPage
}
const Page = (props) => {
const Handler = PAGES[props.page] || ContactPage
return <Handler {...props} />
}
// The keys of the PAGES object can be used in the prop types to catch dev-time errors.
Page.propTypes = {
page: PropTypes.oneOf(Object.keys(PAGES)).isRequired
}
The reason behind for this is that setState()
is an asynchronous operation. React batches state changes for performance reasons, so the state may not change immediately after setState()
is called. That means you should not rely on the current state when calling setState()
since you can't be sure what that state will be. The solution is to pass a function to setState()
, with the previous state as an argument. By doing this you can avoid issues with the user getting the old state value on access due to the asynchronous nature of setState()
.
Let's say the initial count value is zero. After three consecutive increment operations, the value is going to be incremented only by one.
// assuming this.state.count === 0
this.setState({ count: this.state.count + 1 })
this.setState({ count: this.state.count + 1 })
this.setState({ count: this.state.count + 1 })
// this.state.count === 1, not 3
If we pass a function to setState()
, the count gets incremented correctly.
this.setState((prevState, props) => ({
count: prevState.count + props.increment
}))
// this.state.count === 3 as expected
(OR)
setState()
?React may batch multiple setState()
calls into a single update for performance. Because this.props
and this.state
may be updated asynchronously, you should not rely on their values for calculating the next state.
This counter example will fail to update as expected:
// Wrong
this.setState({
counter: this.state.counter + this.props.increment,
})
The preferred approach is to call setState()
with function rather than object. That function will receive the previous state as the first argument, and the props at the time the update is applied as the second argument.
// Correct
this.setState((prevState, props) => ({
counter: prevState.counter + props.increment
}))
React.StrictMode
is a useful component for highlighting potential problems in an application. Just like <Fragment>
, <StrictMode>
does not render any extra DOM elements. It activates additional checks and warnings for its descendants. These checks apply for development mode only.
import React from 'react'
function ExampleApplication() {
return (
<div>
<Header />
<React.StrictMode>
<div>
<ComponentOne />
<ComponentTwo />
</div>
</React.StrictMode>
<Header />
</div>
)
}
In the example above, the strict mode checks apply to <ComponentOne>
and <ComponentTwo>
components only.
Mixins are a way to totally separate components to have a common functionality. Mixins should not be used and can be replaced with higher-order components or decorators.
One of the most commonly used mixins is PureRenderMixin
. You might be using it in some components to prevent unnecessary re-renders when the props and state are shallowly equal to the previous props and state:
const PureRenderMixin = require('react-addons-pure-render-mixin')
const Button = React.createClass({
mixins: [PureRenderMixin],
// ...
})
<!-- TODO: mixins are deprecated -->
The primary use case for isMounted()
is to avoid calling setState()
after a component has been unmounted, because it will emit a warning.
if (this.isMounted()) {
this.setState({...})
}
Checking isMounted()
before calling setState()
does eliminate the warning, but it also defeats the purpose of the warning. Using isMounted()
is a code smell because the only reason you would check is because you think you might be holding a reference after the component has unmounted.
An optimal solution would be to find places where setState()
might be called after a component has unmounted, and fix them. Such situations most commonly occur due to callbacks, when a component is waiting for some data and gets unmounted before the data arrives. Ideally, any callbacks should be canceled in componentWillUnmount()
, prior to unmounting.
Pointer Events provide a unified way of handling all input events. In the old days we had a mouse and respective event listeners to handle them but nowadays we have many devices which don't correlate to having a mouse, like phones with touch surface or pens. We need to remember that these events will only work in browsers that support the Pointer Events specification.
The following event types are now available in React DOM:
onPointerDown
onPointerMove
onPointerUp
onPointerCancel
onGotPointerCapture
onLostPointerCapture
onPointerEnter
onPointerLeave
onPointerOver
onPointerOut
If you are rendering your component using JSX, the name of that component has to begin with a capital letter otherwise React will throw an error as an unrecognized tag. This convention is because only HTML elements and SVG tags can begin with a lowercase letter.
class SomeComponent extends Component {
// Code goes here
}
You can define component class which name starts with lowercase letter, but when it's imported it should have capital letter. Here lowercase is fine:
class myComponent extends Component {
render() {
return <div />
}
}
export default myComponent
While when imported in another file it should start with capital letter:
import MyComponent from './MyComponent'
The component names should start with an uppercase letter but there are few exceptions to this convention. The lowercase tag names with a dot (property accessors) are still considered as valid component names. For example, the below tag can be compiled to a valid component,
render() {
return (
<obj.component/> // `React.createElement(obj.component)`
)
}
Yes. In the past, React used to ignore unknown DOM attributes. If you wrote JSX with an attribute that React doesn't recognize, React would just skip it.
For example, let's take a look at the below attribute:
<div mycustomattribute={'something'} />
Would render an empty div to the DOM with React v15:
<div />
In React v16 any unknown attributes will end up in the DOM:
<div mycustomattribute='something' />
This is useful for supplying browser-specific non-standard attributes, trying new DOM APIs, and integrating with opinionated third-party libraries.
You should initialize state in the constructor when using ES6 classes, and getInitialState()
method when using React.createClass()
.
Using ES6 classes:
class MyComponent extends React.Component {
constructor(props) {
super(props)
this.state = { /* initial state */ }
}
}
Using React.createClass()
:
const MyComponent = React.createClass({
getInitialState() {
return { /* initial state */ }
}
})
Note: React.createClass()
is deprecated and removed in React v16. Use plain JavaScript classes instead.
By default, when your component's state or props change, your component will re-render. If your render()
method depends on some other data, you can tell React that the component needs re-rendering by calling forceUpdate()
.
component.forceUpdate(callback)
It is recommended to avoid all uses of forceUpdate()
and only read from this.props
and this.state
in render()
.
When you want to access this.props
in constructor()
then you should pass props to super()
method.
Using super(props)
:
class MyComponent extends React.Component {
constructor(props) {
super(props)
console.log(this.props) // { name: 'John', ... }
}
}
Using super()
:
class MyComponent extends React.Component {
constructor(props) {
super()
console.log(this.props) // undefined
}
}
Outside constructor()
both will display same value for this.props
.
You can simply use Array.prototype.map
with ES6 arrow function syntax.
For example, the items
array of objects is mapped into an array of components:
<tbody>
{items.map(item => <SomeComponent key={item.id} name={item.name} />)}
</tbody>
But you can't iterate using for
loop:
<tbody>
for (let i = 0; i < items.length; i++) {
<SomeComponent key={items[i].id} name={items[i].name} />
}
</tbody>
This is because JSX tags are transpiled into function calls, and you can't use statements inside expressions. This may change thanks to do
expressions which are stage 1 proposal.
React (or JSX) doesn't support variable interpolation inside an attribute value. The below representation won't work:
<img className='image' src='images/{this.props.image}' />
But you can put any JS expression inside curly braces as the entire attribute value. So the below expression works:
<img className='image' src={'images/' + this.props.image} />
Using template strings will also work:
<img className='image' src={`images/${this.props.image}`} />
If you want to pass an array of objects to a component with a particular shape then use React.PropTypes.shape()
as an argument to React.PropTypes.arrayOf()
.
ReactComponent.propTypes = {
arrayWithShape: React.PropTypes.arrayOf(React.PropTypes.shape({
color: React.PropTypes.string.isRequired,
fontSize: React.PropTypes.number.isRequired
})).isRequired
}
You shouldn't use curly braces inside quotes because it is going to be evaluated as a string.
<div className="btn-panel {this.props.visible ? 'show' : 'hidden'}">
Instead you need to move curly braces outside (don't forget to include spaces between class names):
<div className={'btn-panel ' + (this.props.visible ? 'show' : 'hidden')}>
Template strings will also work:
<div className={`btn-panel ${this.props.visible ? 'show' : 'hidden'}`}>
The react
package contains React.createElement()
, React.Component
, React.Children
, and other helpers related to elements and component classes. You can think of these as the isomorphic or universal helpers that you need to build components. The react-dom
package contains ReactDOM.render()
, and in react-dom/server
we have server-side rendering support with ReactDOMServer.renderToString()
and ReactDOMServer.renderToStaticMarkup()
.
The React team worked on extracting all DOM-related features into a separate library called ReactDOM. React v0.14 is the first release in which the libraries are split. By looking at some of the packages, react-native
, react-art
, react-canvas
, and react-three
, it has become clear that the beauty and essence of React has nothing to do with browsers or the DOM.
To build more environments that React can render to, React team planned to split the main React package into two: react
and react-dom
. This paves the way to writing components that can be shared between the web version of React and React Native.
If you try to render a <label>
element bound to a text input using the standard for
attribute, then it produces HTML missing that attribute and prints a warning to the console.
<label for={'user'}>{'User'}</label>
<input type={'text'} id={'user'} />
Since for
is a reserved keyword in JavaScript, use htmlFor
instead.
<label htmlFor={'user'}>{'User'}</label>
<input type={'text'} id={'user'} />
You can use spread operator in regular React:
<button style={{...styles.panel.button, ...styles.panel.submitButton}}>{'Submit'}</button>
If you're using React Native then you can use the array notation:
<button style={[styles.panel.button, styles.panel.submitButton]}>{'Submit'}</button>
You can listen to the resize
event in componentDidMount()
and then update the dimensions (width
and height
). You should remove the listener in componentWillUnmount()
method.
class WindowDimensions extends React.Component {
constructor(props){
super(props);
this.updateDimensions = this.updateDimensions.bind(this);
}
componentWillMount() {
this.updateDimensions()
}
componentDidMount() {
window.addEventListener('resize', this.updateDimensions)
}
componentWillUnmount() {
window.removeEventListener('resize', this.updateDimensions)
}
updateDimensions() {
this.setState({width: window.innerWidth, height: window.innerHeight})
}
render() {
return <span>{this.state.width} x {this.state.height}</span>
}
}
When you use setState()
the current and previous states are merged. replaceState()
throws out the current state, and replaces it with only what you provide. Usually setState()
is used unless you really need to remove all previous keys for some reason. You can also set state to false
/null
in setState()
instead of using replaceState()
.
The componentDidUpdate
lifecycle method will be called when state changes. You can compare provided state and props values with current state and props to determine if something meaningful changed.
componentDidUpdate(object prevProps, object prevState)
Note: The previous releases of ReactJS also uses componentWillUpdate(object nextProps, object nextState)
for state changes. It has been deprecated in latest releases.
The better approach is to use Array.prototype.filter()
method.
For example, let's create a removeItem()
method for updating the state.
removeItem(index) {
this.setState({
data: this.state.data.filter((item, i) => i !== index)
})
}
It is possible with latest version (>=16.2). Below are the possible options:
render() {
return false
}
render() {
return null
}
render() {
return []
}
render() {
return <React.Fragment></React.Fragment>
}
render() {
return <></>
}
Returning undefined
won't work.
We can use <pre>
tag so that the formatting of the JSON.stringify()
is retained:
const data = { name: 'John', age: 42 }
class User extends React.Component {
render() {
return (
<pre>
{JSON.stringify(data, null, 2)}
</pre>
)
}
}
React.render(<User />, document.getElementById('container'))
The React philosophy is that props should be immutable and top-down. This means that a parent can send any prop values to a child, but the child can't modify received props.
You can do it by creating ref for input
element and using it in componentDidMount()
:
class App extends React.Component{
componentDidMount() {
this.nameInput.focus()
}
render() {
return (
<div>
<input
defaultValue={'Won\'t focus'}
/>
<input
ref={(input) => this.nameInput = input}
defaultValue={'Will focus'}
/>
</div>
)
}
}
ReactDOM.render(<App />, document.getElementById('app'))
Also in Functional component (react 16.08 and above)
import React, {useEffect, useRef} from 'react';
const App = () => {
const inputElRef = useRef(null)
useEffect(()=>{
inputElRef.current.focus()
}, [])
return(
<div>
<input
defaultValue={'Won\'t focus'}
/>
<input
ref={inputElRef}
defaultValue={'Will focus'}
/>
</div>
)
}
ReactDOM.render(<App />, document.getElementById('app'))
Calling setState()
with an object to merge with state:
Using Object.assign()
to create a copy of the object:
const user = Object.assign({}, this.state.user, { age: 42 })
this.setState({ user })
Using spread operator:
const user = { ...this.state.user, age: 42 }
this.setState({ user })
Calling setState()
with a function:
this.setState(prevState => ({
user: {
...prevState.user,
age: 42
}
}))
You can use React.version
to get the version.
const REACT_VERSION = React.version
ReactDOM.render(
<div>{`React version: ${REACT_VERSION}`}</div>,
document.getElementById('app')
)
There are approaches to include polyfills in create-react-app,
core-js
:Create a file called (something like) polyfills.js
and import it into root index.js
file. Run npm install core-js
or yarn add core-js
and import your specific required features.
import 'core-js/fn/array/find'
import 'core-js/fn/array/includes'
import 'core-js/fn/number/is-nan'
Use the polyfill.io CDN to retrieve custom, browser-specific polyfills by adding this line to index.html
:
<script src='https://cdn.polyfill.io/v2/polyfill.min.js?features=default,Array.prototype.includes'></script>
In the above script we had to explicitly request the Array.prototype.includes
feature as it is not included in the default feature set.
You just need to use HTTPS=true
configuration. You can edit your package.json
scripts section:
"scripts": {
"start": "set HTTPS=true && react-scripts start"
}
or just run set HTTPS=true && npm start
Create a file called .env
in the project root and write the import path:
NODE_PATH=src/app
After that restart the development server. Now you should be able to import anything inside src/app
without relative paths.
Add a listener on the history
object to record each page view:
history.listen(function (location) {
window.ga('set', 'page', location.pathname + location.search)
window.ga('send', 'pageview', location.pathname + location.search)
})
You need to use setInterval()
to trigger the change, but you also need to clear the timer when the component unmounts to prevent errors and memory leaks.
componentDidMount() {
this.interval = setInterval(() => this.setState({ time: Date.now() }), 1000)
}
componentWillUnmount() {
clearInterval(this.interval)
}
React does not apply vendor prefixes automatically. You need to add vendor prefixes manually.
<div style={{
transform: 'rotate(90deg)',
WebkitTransform: 'rotate(90deg)', // note the capital 'W' here
msTransform: 'rotate(90deg)' // 'ms' is the only lowercase vendor prefix
}} />
You should use default for exporting the components
import React from 'react'
import User from 'user'
export default class MyProfile extends React.Component {
render(){
return (
<User type="customer">
//...
</User>
)
}
}
With the export specifier, the MyProfile is going to be the member and exported to this module and the same can be imported without mentioning the name in other components.
React's reconciliation algorithm assumes that without any information to the contrary, if a custom component appears in the same place on subsequent renders, it's the same component as before, so reuses the previous instance rather than creating a new one.
You can use ES7 static
field to define constant.
class MyComponent extends React.Component {
static DEFAULT_PAGINATION = 10
}
You could use the ref prop to acquire a reference to the underlying HTMLInputElement
object through a callback, store the reference as a class property, then use that reference to later trigger a click from your event handlers using the HTMLElement.click
method.
This can be done in two steps:
Create ref in render method:
<input ref={input => this.inputElement = input} />
Apply click event in your event handler:
this.inputElement.click()
If you want to use async
/await
in React, you will need Babel and transform-async-to-generator plugin. React Native ships with Babel and a set of transforms.
There are two common practices for React project file structure.
One common way to structure projects is locate CSS, JS, and tests together, grouped by feature or route.
common/
├─ Avatar.js
├─ Avatar.css
├─ APIUtils.js
└─ APIUtils.test.js
feed/
├─ index.js
├─ Feed.js
├─ Feed.css
├─ FeedStory.js
├─ FeedStory.test.js
└─ FeedAPI.js
profile/
├─ index.js
├─ Profile.js
├─ ProfileHeader.js
├─ ProfileHeader.css
└─ ProfileAPI.js
Another popular way to structure projects is to group similar files together.
api/
├─ APIUtils.js
├─ APIUtils.test.js
├─ ProfileAPI.js
└─ UserAPI.js
components/
├─ Avatar.js
├─ Avatar.css
├─ Feed.js
├─ Feed.css
├─ FeedStory.js
├─ FeedStory.test.js
├─ Profile.js
├─ ProfileHeader.js
└─ ProfileHeader.css
React Transition Group and React Motion are popular animation packages in React ecosystem.
It is recommended to avoid hard coding style values in components. Any values that are likely to be used across different UI components should be extracted into their own modules.
For example, these styles could be extracted into a separate component:
export const colors = {
white,
black,
blue
}
export const space = [
0,
8,
16,
32,
64
]
And then imported individually in other components:
import { space, colors } from './styles'
ESLint is a popular JavaScript linter. There are plugins available that analyse specific code styles. One of the most common for React is an npm package called eslint-plugin-react
. By default, it will check a number of best practices, with rules checking things from keys in iterators to a complete set of prop types.
Another popular plugin is eslint-plugin-jsx-a11y
, which will help fix common issues with accessibility. As JSX offers slightly different syntax to regular HTML, issues with alt
text and tabindex
, for example, will not be picked up by regular plugins.
You can use AJAX libraries such as Axios, jQuery AJAX, and the browser built-in fetch
. You should fetch data in the componentDidMount()
lifecycle method. This is so you can use setState()
to update your component when the data is retrieved.
For example, the employees list fetched from API and set local state:
class MyComponent extends React.Component {
constructor(props) {
super(props)
this.state = {
employees: [],
error: null
}
}
componentDidMount() {
fetch('https://api.example.com/items')
.then(res => res.json())
.then(
(result) => {
this.setState({
employees: result.employees
})
},
(error) => {
this.setState({ error })
}
)
}
render() {
const { error, employees } = this.state
if (error) {
return <div>Error: {error.message}</div>;
} else {
return (
<ul>
{employees.map(employee => (
<li key={employee.name}>
{employee.name}-{employee.experience}
</li>
))}
</ul>
)
}
}
}
Render Props is a simple technique for sharing code between components using a prop whose value is a function. The below component uses render prop which returns a React element.
<DataProvider render={data => (
<h1>{`Hello ${data.target}`}</h1>
)}/>
Libraries such as React Router and DownShift are using this pattern.