![]() |
Logo of ReactJS |
React, (also known as React.js or ReactJS) is a powerful JavaScript Library used to create SPA (Single Page Applications) *Web Applications*. React is a open-source Front-end JavaScript library for building user interfaces based on components. ReactJS is firstly introduced by Meta in the year of 2013, the parent company of Facebook and Instagram. The original author of ReactJS is Jordan Walke. ReactJS is maintained by Meta and it's community (formerly Facebook). ReactJS also used as a powerful JavaScript framework. Even Facebook's website uses ReactJS as an integrated script in the application code. Not only does Facebook itself use the framework, but so does Instagram, AirBnB, and Uber Eats.
Quick Information across the Web :
Original author(s) : Jordan Walke
Developer(s) : Meta and community
Initial release date : May 29, 2013; 10 years ago
Stable release : 18.2.0 / 14 June, 2022; 13 months ago
Repository : github.com/facebook/react
Written in : JavaScript
Platform : Web platform
Type : JavaScript Library
License : MIT License
Website : react.dev
React can be used to develop single-page, mobile, or server-rendered applications with frameworks like Next.js. Because React is only concerned with the user interface and rendering components to the DOM (Document Object Model), React applications often rely on libraries for routing and other client-side functionality.
• Basic usage
The following is a rudimentary example of using React for the web, written in JSX and JavaScript.
```
import React from 'react';
import ReactDOM from 'react-dom/client';
/** A pure component that displays a message */
const Greeting = () => {
return (
<div className="hello-world">
<h1>Hello, world!</h1>
</div>
);
};
/** The main app component */
const App = () => {
return <Greeting />;
};
/** React is rendered to a root element in the HTML page */
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<App />);
```
based on the HTML document below.
```
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>React App</title>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
</body>
</html>
```
The `Greeting`function is a React component that displays the famous introductory ''Hello, world".
When displayed on a web browser, the result will be a rendering of :
```
<div class="hello-world">
<h1>Hello, world!</h1>
</div>
```
• Notable features
Declarative
React adheres to the declarative programming paradigm. Developers design views for each state of an application, and React updates and renders components when data changes. This is in contrast with imperative programming.
Components
React code is made of entities called components. These components are modular and reusable. React applications typically consist of many layers of components. The components are rendered to a root element in the DOM using the React DOM library. When rendering a component, values are passed between components through props (short for "properties"). Values internal to a component are called its state.
The two primary ways of declaring components in React are through function components and class components.
```
import React from "react";
/** A pure component that displays a message with the current count */
const CountDisplay = props => {
// The count value is passed to this component as props
const { count } = props;
return (<div>The current count is {count}.</div>);
}
/** A component that displays a message that updates each time the button is clicked */
const Counter = () => {
// The React useState Hook is used here to store and update the
// total number of times the button has been clicked.
const [count, setCount] = React.useState(0);
return (
<div className="counter">
<CountDisplay count={count} />
<button onClick={() => setCount(count + 1)}>Add one!</button>
</div>
);
};
```
Function Components
Function components are declared with a function (using JavaScript function syntax or an arrow function expression) that accepts a single "props" argument and returns JSX. From React v16.8 onwards, function components can use state with the `useState` Hook.
```
// Function syntax
function Greeter() {
return <div>Hello World</div>;
}
// Arrow function expression
const Greeter = () => <div>Hello World</div>;
```
React Hooks
On February 16, 2019, React 16.8 was released to the public, introducing React Hooks. Hooks are functions that let developers "hook into" React state and lifecycle features from function components. Notably, Hooks do not work inside classes — they let developers use more features of React without classes.
React provides several built-in Hooks such as
`useState` ,
`useContext` ,
`useReducer` ,
`useMemo` and
`useEffect`.
Others are documented in the Hooks API Reference. `useState` and `useEffect`, which are the most commonly used, are for controlling state and side effects respectively.
Rules of hooks
There are two rules of Hooks which describe the characteristic code patterns that Hooks rely on:
- "Only Call Hooks at the Top Level" — Don't call hooks from inside loops, conditions, or nested statements so that the hooks are called in the same order each render.
- "Only Call Hooks from React Functions" — Don't call hooks from plain JavaScript functions so that stateful logic stays with the component.
Although these rules can't be enforced at runtime, code analysis tools such as linters can be configured to detect many mistakes during development. The rules apply to both usage of Hooks and the implementation of custom Hooks, which may call other Hooks.
Server Components
React Server Components (or "RSC"s) are function components that run exclusively on the server. The concept was first introduced in the talk Data Fetching with Server Components Though a similar concept to Server Side Rendering, RSCs do not send corresponding JavaScript to the client as no hydration occurs. As a result, they have no access to hooks. However, they may be asynchronous function, allowing them to directly perform asynchronous operations :
```
async function MyComponent() {
const message = await fetchMessageFromDb();
return (
<div>Message: {message}</div>
);
}
```
Currently, server components are most readily usable with Next.js.
Class components
Class components are declared using ES6 classes. They behave the same way that function components do, but instead of using Hooks to manage state and lifecycle events, they use the lifecycle methods on the `React.Component` base class.
```
class ParentComponent extends React.Component {
state = { color: 'green' };
render() {
return (
<ChildComponent color={this.state.color} />
);
}
}
```
Routing
React itself does not come with built-in support for routing. React is primarily a library for building user interfaces, and it doesn't include a full-fledged routing solution out of the box.
However, there are popular third-party libraries that can be used to handle routing in React applications. One such library is `react-router` , which provides a comprehensive routing solution for React applications. It allows you to define routes, manage navigation, and handle URL changes in a React-friendly way.
To use `react-router` , you need to install it as a separate package and integrate it into your React application.
1. Install `react-router-dom` using `npm` or `yarn` :
```
npm install react-router-dom
```
```
yarn add react-router-dom
```
2. Set up your routing configuration in your main application file :
```
import React from 'react';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
import Home from './components/Home';
import About from './components/About';
import Contact from './components/Contact';
function App() {
return (
<Router>
<Switch>
<Route exact path="/" component={Home} />
<Route path="/about" component={About} />
<Route path="/contact" component={Contact} />
</Switch>
</Router>
);
}
export default App;
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
import Home from './components/Home';
import About from './components/About';
import Contact from './components/Contact';
function App() {
return (
<Router>
<Switch>
<Route exact path="/" component={Home} />
<Route path="/about" component={About} />
<Route path="/contact" component={Contact} />
</Switch>
</Router>
);
}
export default App;
```
3. Create the components for each route (e.g., Home, About, Contact).
With this setup, when the user navigates to different URLs, the corresponding components will be rendered based on the defined routes.
Virtual DOM
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. This process is called reconciliation. This allows the programmer to write code as if the entire page is rendered on each change, while React only renders the components that actually change. This selective rendering provides a major performance boost.
• Updates
When `ReactDOM.render` is called again for the same component and target, React represents the new UI (User Interface) state in the Virtual DOM and determines which parts (if any) of the living DOM needs to change.
Lifecycle methods for class-based components use a form of hooking that allows the 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
JSX, or JavaScript Syntax Extension, is an extension to the JavaScript language syntax. 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>
);
}
}
render() {
return (
<div>
<p>Header</p>
<p>Content</p>
<p>Footer</p>
</div>
);
}
}
```
Architecture beyond HTML
The basic architecture of React applies beyond rendering HTML in the browser. For example, Facebook has dynamic charts that render to `<canvas>` tags, and Netflix and PayPal use universal loading to render identical HTML on both the server and client.
Server-Side Rendering
Server-side rendering (SSR) refers to the process of rendering a client-side JavaScript application on the server, rather than in the browser. This can improve the performance of the application, especially for users on slower connections or devices.
With SSR, the initial HTML that is sent to the client includes the fully rendered UI of the application. This allows the client's browser to display the UI immediately, rather than having to wait for the JavaScript to download and execute before rendering the UI.
React supports SSR, which allows developers to render React components on the server and send the resulting HTML to the client. This can be useful for improving the performance of the application, as well as for search engine optimization purposes.
```
const express = require('express');
const React = require('react');
const { renderToString } = require('react-dom/server');
const app = express();
app.get('/', (req, res) => {
const html = renderToString(<MyApp />);
res.send(`
<!doctype html>
<html>
<body>
<div id="root">${html}</div>
<script src="/bundle.js"></script>
</body>
</html>
`);
});
app.listen(3000, () => {
console.log('Server listening on port 3000');
});
```
• Common idioms
React does not attempt to provide a complete application library. It is designed specifically for building user interfaces 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.
Unidirectional data flow
To support React's concept of unidirectional data flow (which might be contrasted with AngularJS's bidirectional flow), the Flux architecture was developed as 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. When used with React, this propagation is accomplished through component properties. Since its conception, Flux has been superseded by libraries such as Redux and MobX.
Flux can be considered a variant of the observer pattern.
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` . 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.
In February 2019, `useReducer` was introduced as a React hook in the 16.8 release. It provides an API that is consistent with Redux, enabling developers to create Redux-like stores that are local to component states.
• Future development
Project status can be tracked via the core team discussion forum. However, major changes to React go through the Future of React repository issues and pull requests. This enables the React community to provide feedback on new potential features, experimental APIs and JavaScript syntax improvements.
• History of ReactJS
React was created by Jordan Walke, a software engineer at Meta, who released an early prototype of React called "FaxJS". 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. It was open-sourced at JSConf US in May 2013.
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 set of internal algorithms for rendering, as opposed to React's old rendering algorithm, Stack. React Fiber was to become the foundation of any future improvements and feature development of the React library. The actual syntax for programming with React does not change; only the way that the syntax is executed has changed. React's old rendering system, Stack, was developed at a time when the focus of the system on dynamic change was not understood. Stack was slow to draw complex animation, for example, trying to accomplish all of it in one chunk. Fiber breaks down animation into segments that can be spread out over multiple frames. Likewise, the structure of a page can be broken into segments that may be maintained and updated separately. JavaScript functions and virtual DOM objects are called "fibers", and each can be operated and updated separately, allowing for smoother on-screen rendering.
On September 26, 2017, React 16.0 was released to the public.
On August 10, 2020, the React team announced the first release candidate for React v17.0, notable as the first major release without major changes to the React developer-facing API.
On March 29, 2022, React 18 was released which introduced a new concurrent renderer, automatic batching and support for server side rendering with Suspense.
• Licensing
The initial public release of React in May 2013 used the Apache License 2.0. In October 2014, React 0.12.00 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 :
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.
Based on community feedback, Facebook updated the patent grant in April 2015 to be less ambiguous and more permissive :
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.



React is my favourite JS library.
ReplyDeleteI am the author of this Blogpost.
Delete