What Is React & How Does It Actually Work?
ReactJS is one of the most popular JavaScript libraries for mobile and web application development. Created by Facebook, React contains a collection of reusable JavaScript code snippets called components that are used for user interface (UI) building.
It’s important to note that ReactJS is not a JavaScript framework. That’s because it’s only responsible for rendering the components of an application’s view layer. React is an alternative to frameworks like Angular and Vue, which all allow to create complex functions.
This article will explore React’s features, explain how it works, and go over its benefits for front-end developers. We’ll also cover the differences between ReactJS and React Native regarding their roles in the web and mobile app development industry.
We’ll also explain how to deploy a React application on Hostinger.
Download Glossary For Web Beginners
What Is React – Video Tutorial
In this video tutorial, you’ll learn what is React, why you should use it, and its main features.
React Features
React has some core features that make it stand out from other JavaScript libraries. The following sections will introduce you to these features and explain how they contribute to mobile and web application development.
JSX
JSX is a JavaScript syntax extension used in React element creation. Developers employ it to embed HTML code in JavaScript objects. As JSX accepts valid JavaScript expressions and function embedding, it can simplify complex code structures.
Let’s take a look at a code block that shows how to embed an expression in JSX:
const name = 'John Smith; const element = h1>Hello, {name}/h1>; ReactDOM.render( element, document.getElementById('root') );
In the second line, we call the name variable inside a React element by putting it inside the curly brackets.
Meanwhile, the ReactDOM.render() function renders the React element on the Document Object Model (DOM) tree, describing the UI.
JSX also helps combat Cross-Site Scripting (XSS) attacks. By default, React DOM converts values embedded in JSX to strings before rendering them. Consequently, third parties cannot inject extra code through user input unless it is explicitly written in the application.
Later in the article, we’ll discuss JSX’s role in React component creation in more detail.
Virtual DOM
The Document Object Model (DOM) presents a web page in a data tree structure. ReactJS stores Virtual DOM trees in the memory. By doing so, React can apply updates to specific parts of the data tree, which is faster than re-rendering the entirety of the DOM tree.
Whenever there’s a change in data, ReactJS will generate a new Virtual DOM tree and compare it with the previous one to find the quickest possible way to implement changes in the real DOM. This process is known as diffing.
By making sure that UI manipulation only affects specific sections of the real DOM tree, rendering the updated version takes less time and uses fewer resources. The practice greatly benefits large projects with intense user interaction.
Components and Props
ReactJS divides the UI into isolated reusable pieces of code known as components. React components work similarly to JavaScript functions as they accept arbitrary inputs called properties or props.
Returned React elements determine how the UI will look at the client end. Here’s an example of a function component that returns a React element:
function Welcome(props) { return h1>Hello, {props.name}/h1>; }
It’s possible to have as many components as necessary without cluttering your code.
State Management
A state is a JavaScript object that represents a part of a component. It changes whenever a user interacts with the application, rendering a new UI to reflect the modifications.
State management refers to the practice of managing React application states. It includes storing data in third-party state management libraries and triggering the re-rendering process each time data is changed.
A state management library facilitates communication and data sharing between React components. Several third-party state management libraries are available today, but Redux and Recoil are two of the most popular.
Redux
The Redux state management library has a centralized store, which keeps the state tree of an application predictable. The library also reduces data inconsistency by preventing two components from updating the application’s state simultaneously.
Redux’s architecture supports error logging for easier debugging and has a strict code organization method, simplifying maintenance. Additionally, it features a large number of add-ons and is compatible with all UI layers.
That said, Redux is rather complex and hence suboptimal for small applications with a single data source.
Recoil
Recoil is a JavaScript state management library released by Facebook. It employs pure functions called selectors to calculate data from updateable units of the state known as atoms. Multiple components can subscribe to the same atom and thus share a state.
The use of atoms and selectors prevents redundant states, simplifies code, and eliminates excessive re-renders of React and any child components. Recoil is more suitable for beginners than Redux because its core concepts are considerably easier to grasp.
Programmatic Navigation
Programmatic navigation refers to instances when lines of code create an action that redirects a user. Login and signup actions, for instance, programmatically navigate users to new pages.
React Router, React’s standard library for routing, provides multiple ways of safe programmatic navigation between components without requiring the user to click on a link.
Using a Redirect component is the primary method of programmatic navigation with history.push() being another approach.
In short, the React Router package synchronizes the UI with the URL, giving you control over the look of React applications without depending on links.
Why Use React?
Hundreds of major companies worldwide, such as Netflix, Airbnb, and American Express, use React to build their web applications. In the following sections, we’ll discuss the reasons why so many developers choose ReactJS over its competitors.
1. Easy to Use
Developers with JavaScript knowledge can learn how to use React in no time as it relies on plain JavaScript and a component-based approach. It’s possible to start developing web-based applications with React after just a couple of days of studying it.
Even if you aren’t familiar with JavaScript, tons of websites provide coding lessons for free. Once you know the basics of JavaScript, read up on ReactJS to streamline the front-end development process.
2. Supports Reusable Java Components
React lets you reuse components that have been developed into other applications. Since ReactJS is open source, it’s possible to pre-build components, cutting down on the development time of complex web applications.
What’s more, React allows nesting components in between others to create complex functions without bloating the code. As each component has its own controls, it’s easy to maintain them.
3. Easier Component Writing
Because of JSX integration, it’s easier to write React components – users can create JavaScript objects combined with HTML typography and tags. JSX also simplifies multiple-function rendering, which keeps code lean without reducing the app’s capabilities.
Even though JSX is not the most popular syntax extension, it has proven efficient in special component and dynamic application development.
React’s official command-line interface tool (CLI) called Create React App further streamlines single-page application development. It features a modern build setup process with pre-configured tools and is excellent for learning ReactJS.
4. High Performance
As discussed earlier, Virtual DOM allows ReactJS to update the DOM tree in the most efficient way possible. By storing Virtual DOM in the memory, React eliminates excessive re-rendering that may harm performance.
Additionally, React’s one-way data binding between elements streamlines the debugging process. Any modifications made to child components won’t affect the parent structure, reducing the risk of errors.
5. SEO Friendly
ReactJS may improve the search engine optimization (SEO) of web applications by increasing their performance. Virtual DOM implementation is one of the factors that influence faster page speeds.
Furthermore, React helps search engines navigate web applications by performing server-side rendering. This tackles one of the most significant issues JavaScript-heavy websites encounter, as search engines usually find them challenging and time-consuming to crawl.
How Does React Work?
One of the biggest advantages of using React is that you can infuse HTML code with JavaScript.
Users can create a representation of a DOM node by declaring the Element function in React. The code below contains a combination of HTML and JavaScript:
React.createElement("div", { className: "red" }, "Children Text"); React.createElement(MyCounter, { count: 3 + 5 });
You may have noticed that the syntax of the HTML code above is similar to XML. That said, instead of using the traditional DOM class, React uses className.
JSX tags have a name, children, and attributes. Numeric values and expressions must be written inside curly brackets. The quotation marks in JSX attributes represent strings, similar to JavaScript.
In most cases, React is written using JSX instead of standard JavaScript to simplify components and keep code clean.
Here is an example of React code written using JSX:
MyCounter count={3 + 5} />; var GameScores = {player1: 2,player2: 5}; DashboardUnit data-index="2"> h1>Scores/h1>Scoreboard className="results" scores={GameScores} /> /DashboardUnit>;
The following is a breakdown of the HTML tags above:
- MyCounter> represents a variable called count whose value is a numeric expression.
- GameScores is an object literal that has two prop-value pairs.
- DashboardUnit> is the XML block that is rendered on the page.
- scores={GameScores} is the scores attribute. It gets its value from the GameScores object literal defined earlier.
A React app usually has a single root DOM node. Rendering an element into the DOM will change the user interface of the page.
For instance, the following code displays “Hello World” on the page by rendering the element into a DOM node called root.
div id="root">/div> const element = h1>Hello, world/h1>; ReactDOM.render(element, document.getElementById('root'));
Whenever a React component returns an element, the Virtual DOM will update the real DOM to match.
What About React Native?
React Native is an open-source JavaScript framework built on the React library. Developers use it to create cross-platform React apps for iOS and Android.
React Native uses native Application Programming Interfaces (APIs) to render mobile UI components in Objective-C (iOS) or Java (Android). Because of that, developers can create platform-specific components and share the source code across multiple platforms.
Despite having similarities, React Native is different from ReactJS. Here is a quick comparison of React Native and ReactJS:
ReactJS | React Native |
A JavaScript library. | A JavaScript framework. |
Ideal for building dynamic web applications. | Gives a native feeling to mobile apps’ UI. |
Uses Virtual DOM to render browser code. | Uses native APIs to render code on mobile devices. |
Supports CSS for creating animations. | Requires the animated API to animate components. |
Uses HTML tags. | Doesn’t use HTML tags due to the lack of DOM support. |
Uses CSS for styling. | Uses the JS stylesheet for styling. |
How to Deploy a React Application on Hostinger
You need VPS hosting to make your React app public. Hostinger’s VPS plans come with full root access and are easily scalable, making deployment and server management straightforward and easy.
Deploy a React application on Hostinger by following these steps:
1. Select a VPS template with Ubuntu 22.04 64bit operating system.
2. Using SSH, connect to the operating system:
ssh root@your_server_ip
3. Install a node.js server and a reverse proxy server, and make sure you have removed Apache2:
sudo apt-get purge apache2* curl -sL https://deb.nodesource.com/setup_18.x -o nodesource_setup.sh sudo bash nodesource_setup.sh sudo apt update && sudo apt upgrade -y sudo apt install -y nodejs nginx
4. In order for your Next.js application to work properly, create a fresh Nginx configuration file:
sudo nano /etc/nginx/sites-available/nextjs
5. Next, paste this configuration to the file. Remember to replace your_server_ip with your VPS IP address or your domain name, and save your changes once you’re done.
server { listen 80; server_name your_server_ip; location / { proxy_pass http://localhost:3000; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection 'upgrade'; proxy_set_header Host $host; proxy_cache_bypass $http_upgrade; } }
6. In order to enable the configuration, you need to create a symbolic link:
sudo ln -s /etc/nginx/sites-available/nextjs /etc/nginx/sites-enabled/
7. Restart Nginx with this command:
sudo service nginx restart
8. Follow the prompts and make a new Next.js application:
cd /var/www npx create-next-app@latest nextjs
9. Head to the Next.js application directory:
cd nextjs
10. Next, install application dependencies:
npm install
11. Build your Next.js application with this command:
npm run build
12. Once you’re done, start your Next.js application with the following prompt:
npm start
Your Next.js application is now live and accessible through your domain name or VPS IP address.
Use a process manager like PM2 to automatically restart your application after a server reboot or a crash. PM2 also keeps your Next.js application running in the background of your VPS. Install PM2 like this:
1. Run the following command on your VPS:
cd ~ sudo npm install -g pm2
2. Go to the Next.js application directory:
cd /var/www/nextjs
3. Use PM2 to start your Next.js application:
pm2 start npm --name "nextjs" -- start
Make sure PM2 starts on boot – use this command to generate a script to copy and paste into your terminal:
pm2 startup
Save all current PM2 processes with this command:
pm2 save
Conclusion
ReactJS is a robust JavaScript library used in dynamic web application development. It makes JavaScript coding more simple and improves your application’s performance and SEO, among other benefits.
ReactJS helps streamline the debugging process and reduces the risk of errors by engaging in one-way data binding.
Here’s a recap of why you may want to use React:
- It’s easy to use and learn, with plenty of coding lessons available online.
- It supports reusable components, cutting down development time.
- JSX makes it easier to code and render elements.
- Virtual DOM eliminates excessive re-rendering, ensuring the high performance of your application.
- React helps search engines crawl your web application, boosting its SEO.
We hope this article has helped you understand React JS and its functions in web development. If you have any notes or questions, leave them in the comment section below.
Comments
June 03 2022
The article is incomplete. It talks about how to proceed if there is a VPS, but it doesn't make it clear what to do when there isn't.
June 07 2022
Hi there! The VPS and node.js mention is just a suggestion. If you're running your website on a shared or cloud plan, you will not be able to use node.js, but you can still use React with just JS - you can find more about it here 😊