1000/1000
Hot
Most Recent
React (also known as React.js or ReactJS) is an open-source JavaScript library for building user interfaces. It is maintained by Facebook and a community of individual developers and companies. React can be used as a base in the development of single-page or mobile applications. However, React is only concerned with rendering data to the DOM, and so creating React applications usually requires the use of additional libraries for state management and routing. Redux and React Router are respective examples of such libraries.
The following is a rudimentary example of React usage in HTML with JSX and JavaScript.
<div id="myReactApp"></div> <script type="text/babel"> function Greeter(props) { return <h1>{props.greeting}</h1> } var App = <Greeter greeting="Hello World!" />; ReactDOM.render(App, document.getElementById('myReactApp')); </script>
The Greeter
function is a React component that accepts a property greeting
. The variable App
is an instance of the Greeter
component where the greeting
property is set to 'Hello World!'
. The ReactDOM.render
method then renders our Greeter component inside the DOM element with id myReactApp
.
When displayed in a web browser the result will be
<div id="myReactApp"> <h1>Hello World!</h1> </div>
React code is made of entities called components. Components can be rendered to a particular element in the DOM using the React DOM library. When rendering a component, one can pass in values that are known as "props"[1]:
ReactDOM.render(<Greeter greeting="Hello World!" />, document.getElementById('myReactApp'));
The two primary ways of declaring components in React is via functional components and class-based components.
Functional components are declared with a function that then returns some JSX.
const Greeting = (props) => <div>Hello, {props.name}!</div>;
Class-based components are declared using ES6 classes.
class ParentComponent extends React.Component { state = { color: 'green' }; render() { return ( <ChildComponent color={this.state.color} /> ); } }
Another notable feature is the use of a virtual Document Object Model, or virtual DOM. React creates an in-memory data-structure cache, computes the resulting differences, and then updates the browser's displayed DOM efficiently.[2]. This process is called reconciliation. This allows the programmer to write code as if the entire page is rendered on each change, while the React libraries only render subcomponents that actually change. This selective rendering provides a major performance boost. It saves the effort of recalculating the CSS style, layout for the page and rendering for the entire page.
Lifecycle methods use a form of hooking that allows execution of code at set points during a component's lifetime.
shouldComponentUpdate
allows the developer to prevent unnecessary re-rendering of a component by returning false if a render is not required.componentDidMount
is called once the component has "mounted" (the component has been created in the user interface, often by associating it with a DOM node). This is commonly used to trigger data loading from a remote source via an API.componentWillUnmount
is called immediately before the component is torn down or "unmounted". This is commonly used to clear resource demanding dependencies to the component that will not simply be removed with the unmounting of the component (e.g., removing any setInterval()
instances that are related to the component, or an "eventListener" set on the "document" because of the presence of the component)render
is the most important lifecycle method and the only required one in any component. It is usually called every time the component's state is updated, which should be reflected in the user interface.JSX, or JavaScript XML , is an extension to the JavaScript language syntax.[3] Similar in appearance to HTML, JSX provides a way to structure component rendering using syntax familiar to many developers. React components are typically written using JSX, although they do not have to be (components may also be written in pure JavaScript). JSX is similar to another extension syntax created by Facebook for PHP called XHP.
An example of JSX code:
class App extends React.Component { render() { return ( <div> <p>Header</p> <p>Content</p> <p>Footer</p> </div> ); } }
Multiple elements on the same level need to be wrapped in a single container element such as the <div>
element shown above, or returned as an array.[4]
JSX provides a range of element attributes designed to mirror those provided by HTML. Custom attributes can also be passed to the component.[5] All attributes will be received by the component as props.
JavaScript expressions (but not statements) can be used inside JSX with curly brackets {}
:
<h1>{10+1}</h1>
The example above will render
<h1>11</h1>
If–else statements cannot be used inside JSX but conditional expressions can be used instead. The example below will render { i === 1 ? 'true' : 'false' }
as the string 'true'
because i
is equal to 1.
class App extends React.Component { render() { const i = 1; return ( <div> <h1>{ i === 1 ? 'true' : 'false' }</h1> </div> ); } }
The above will render:
<div> <h1>true</h1> </div>
Functions and JSX can be used in conditionals:
class App extends React.Component { render() { const sections = [1, 2, 3]; return ( <div> {sections.length > 0 && sections.map(n => ( /* 'key' is used by react to keep track of list items and their changes */ /* Each 'key' must be unique */ <div key={"section-" + n}>Section {n}</div> ))} </div> ); } }
The above will render:
<div> <div>Section 1</div> <div>Section 2</div> <div>Section 3</div> </div>
Code written in JSX requires conversion with a tool such as Babel before it can be understood by web browsers.[6] This processing is generally performed during a software build process before the application is deployed.
The basic architecture of React applies beyond rendering HTML in the browser. For example, Facebook has dynamic charts that render to <canvas>
tags,[7] and Netflix and PayPal use universal loading to render identical HTML on both the server and client.[8][9]
Hooks are functions that let developers "hook into" React state and lifecycle features from function components.[10] They make codes readable and easily understandable. Hooks don’t work inside classes — they let you use React without classes.[11]
React provides a few built-in Hooks like useState
,[12] useContext
, useReducer
and useEffect
[13] to name a few. They are all stated in the Hooks API Reference.[14] useState
and useEffect
, which are the most used, are for controlling states and side effects respectively in React Components.
There are also rules of hooks[15] which must be followed before they can be used.
Building your own hooks[16] which are called custom hooks lets you extract component logic into reusable functions. A custom Hook is a JavaScript function whose name starts with ”use” and that may call other Hooks. The rules of hooks also apply to them.
React does not attempt to provide a complete "application library". It is designed specifically for building user interfaces[17] and therefore does not include many of the tools some developers might consider necessary to build an application. This allows the choice of whichever libraries the developer prefers to accomplish tasks such as performing network access or local data storage. Common patterns of usage have emerged as the library matures.
To support React's concept of unidirectional data flow (which might be contrasted with AngularJS's bidirectional flow), the Flux architecture represents an alternative to the popular model-view-controller architecture. Flux features actions which are sent through a central dispatcher to a store, and changes to the store are propagated back to the view.[18] When used with React, this propagation is accomplished through component properties.
Flux can be considered a variant of the observer pattern.[19]
A React component under the Flux architecture should not directly modify any props passed to it, but should be passed callback functions that create actions which are sent by the dispatcher to modify the store. The action is an object whose responsibility is to describe what has taken place: for example, an action describing one user "following" another might contain a user id, a target user id, and the type USER_FOLLOWED_ANOTHER_USER
.[20] The stores, which can be thought of as models, can alter themselves in response to actions received from the dispatcher.
This pattern is sometimes expressed as "properties flow down, actions flow up". Many implementations of Flux have been created since its inception, perhaps the most well-known being Redux, which features a single store, often called a single source of truth.[21]
Project status can be tracked via the core team discussion forum.[22] However, major changes to React go through the Future of React repository issues and pull requests.[23][24] This enables the React community to provide feedback on new potential features, experimental APIs and JavaScript syntax improvements.
React was created by Jordan Walke, a software engineer at Facebook, who released an early prototype of React called "FaxJS".[25][26] He was influenced by XHP, an HTML component library for PHP. It was first deployed on Facebook's News Feed in 2011 and later on Instagram in 2012.[27] It was open-sourced at JSConf US in May 2013.[26]
React Native, which enables native Android, iOS, and UWP development with React, was announced at Facebook's React Conf in February 2015 and open-sourced in March 2015.
On April 18, 2017, Facebook announced React Fiber, a new core algorithm of React library for building user interfaces.[28] React Fiber was to become the foundation of any future improvements and feature development of the React library.[29]
On September 26, 2017, React 16.0 was released to the public.[30]
On February 16, 2019, React 16.8 was released to the public.[31] The release introduced React Hooks.[32]
The initial public release of React in May 2013 used the Apache License 2.0. In October 2014, React 0.12.0 replaced this with the 3-clause BSD license and added a separate PATENTS text file that permits usage of any Facebook patents related to the software:[33]
The license granted hereunder will terminate, automatically and without notice, for anyone that makes any claim (including by filing any lawsuit, assertion or other action) alleging (a) direct, indirect, or contributory infringement or inducement to infringe any patent: (i) by Facebook or any of its subsidiaries or affiliates, whether or not such claim is related to the Software, (ii) by any party if such claim arises in whole or in part from any software, product or service of Facebook or any of its subsidiaries or affiliates, whether or not such claim is related to the Software, or (iii) by any party relating to the Software; or (b) that any right in any patent claim of Facebook is invalid or unenforceable.
This unconventional clause caused some controversy and debate in the React user community, because it could be interpreted to empower Facebook to revoke the license in many scenarios, for example, if Facebook sues the licensee prompting them to take "other action" by publishing the action on a blog or elsewhere. Many expressed concerns that Facebook could unfairly exploit the termination clause or that integrating React into a product might complicate a startup company's future acquisition.[34]
Based on community feedback, Facebook updated the patent grant in April 2015 to be less ambiguous and more permissive:[35]
The license granted hereunder will terminate, automatically and without notice, if you (or any of your subsidiaries, corporate affiliates or agents) initiate directly or indirectly, or take a direct financial interest in, any Patent Assertion: (i) against Facebook or any of its subsidiaries or corporate affiliates, (ii) against any party if such Patent Assertion arises in whole or in part from any software, technology, product or service of Facebook or any of its subsidiaries or corporate affiliates, or (iii) against any party relating to the Software. [...] A "Patent Assertion" is any lawsuit or other action alleging direct, indirect, or contributory infringement or inducement to infringe any patent, including a cross-claim or counterclaim.[36]
The Apache Software Foundation considered this licensing arrangement to be incompatible with its licensing policies, as it "passes along risk to downstream consumers of our software imbalanced in favor of the licensor, not the licensee, thereby violating our Apache legal policy of being a universal donor", and "are not a subset of those found in the [Apache License 2.0], and they cannot be sublicensed as [Apache License 2.0]".[37] In August 2017, Facebook dismissed the Apache Foundation's downstream concerns and refused to reconsider their license.[38][39] The following month, WordPress decided to switch its Gutenberg and Calypso projects away from React.[40]
On September 23, 2017, Facebook announced that the following week, it would re-license Flow, Jest, React, and Immutable.js under a standard MIT License; the company stated that React was "the foundation of a broad ecosystem of open source software for the web", and that they did not want to "hold back forward progress for nontechnical reasons".[41]
On September 26, 2017, React 16.0.0 was released with the MIT license.[42] The MIT license change has also been backported to the 15.x release line with React 15.6.2.[43]