Why React?
Why do we need React? Transitioning from pure Javascript to React.
In the following articles lies how we build web applications using HTML, CSS, and pure Javascript. And then we slowly move on to understand why we need React, and how React solves those problems.
Type of programming
Let's suppose you are given a task to dynamically create an h1 tag inside a div having the id "app" and then add text inside it using pure Javascript. In general, the code you'll write will be something like this :
<script type="text/javascript">
const app = document.getElementById('app');
const header = document.createElement('h1');
const headerContent = document.createTextNode('I am Thanos');
header.appendChild(headerContent);
app.appendChild(header);
</script>
Now if you look at the above script, you'll notice that you have described step by step process to let the browser know HOW to perform the task. This type of programming is called Imperative Programming, which plain Javascript implements.
Now imagine if there is someone who can do this task on your behalf and you just have to tell them WHAT task to perform. This type of programming is called Declarative Programming, in which you simply declare what needs to be done. And React works exactly on this thing. The above tasks can be done by React as follows:
<script type="text/javascript">
const app = document.getElementById('app');
ReactDOM.render(<h1>I am Thanos</h1>, app);
</script>
If you notice, we simply declared that I want to show <h1> tag with some text, inside a div having id "app". This approach makes the code less verbose.
And this is the basis of Code Reusability which React offers. It consists of code snippets that perform tasks on your behalf.
Rendering webpage and Updating UI
How do HTML, CSS, and pure Javascript render a web page?
The browser parses the HTML document to create the Document Object Model(DOM), which is a tree-like structure with each element as a node in the tree. After that, it parses the CSS file into a style tree which represents style rules applied to each element in the DOM. This combination of style tree and DOM is called a Render tree.
After that, the browser calculates the layout(calculating the size and positions of each element in the DOM), followed by the painting of pixels on the screen(visual representation). Now comes the Javascript.
The javascript file associated with the HTML document modifies the actual DOM and any modification triggers the process called Reflow. During Reflow, the browser recalculates the layout and repaints the affected elements.
Moreover, when JavaScript introduces any dynamic changes, the browser updates the Render tree, recalculates the layout, and repaints the affected part.
How React render a web page?
Well, a complete article can be written on this thing, but in short, React creates a virtual DOM. Whenever a change happens it uses the diffing algorithm to identify the exact element that gets changed and instead of updating the entire DOM it only updates the corresponding node in the actual DOM
Now this thing saves a lot of time and helps to improve performance, as the browser doesn't have to go through the process of Reflow for the entire web page.
State Management
The very basic example of state management that we all know is building a counter. Let's create a counter using pure javascript
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Plain JavaScript State Management</title>
</head>
<body>
<div id="app">
<p>Count: <span id="countDisplay"></span></p>
<button onclick="increment()">Increment</button>
<button onclick="decrement()">Decrement</button>
</div>
<script>
// State object
let state = {
count: 0
};
// Function to update the display
function updateDisplay() {
document.getElementById('countDisplay').textContent = state.count;
}
// Function to handle incrementing the count
function increment() {
state.count += 1;
updateDisplay();
}
// Function to handle decrementing the count
function decrement() {
state.count -= 1;
updateDisplay();
}
// Initial display update
updateDisplay();
</script>
</body>
</html>
Let's build the same counter using React
import React, { useState } from 'react';
function App() {
// State using the useState hook
const [count, setCount] = useState(0);
return (
<div>
<p>Count: <span>{count}</span></p>
<button onClick={() => {setCount(count+1)}>Increment</button>
<button onClick={() => {setCount(count-1)}>Decrement</button>
</div>
);
}
export default App;
In the above example, you can again notice the difference that React provides a reusable snippet of code called as "useState" hook, which takes care of updating of state. Whereas in plain javascript, we need to define each and every step of how to update the state (imperative programming).
Now the problem with the javascript way of managing the state is that, firstly we have to declare step by step process of managing the state making our code verbose. Secondly, as our app becomes more and more complex, the chance of manual errors and writing functions to do the same becomes increasingly difficult. Due to this, sometimes even React alone makes it very difficult to manage global states and we need to use third-party libraries such as Redux, Recoil, etc.
Data Binding
Data binding refers to the synchronization of data between the model (or source of data) and the view (or UI).
In plain javascript, when underlying data changes you have to manually manipulate the DOM element by selecting the element and updating its content or attributes. Also, you need to set up event listeners for user interactions (e.g., input changes) and update the data accordingly.
React implements One-way data binding. In React apps, data flows in one direction from top to down in the DOM tree. Data propagates from parent component to child components. You write components based on the current state of the data, and when the data changes React takes care of updating the DOM.
Summary
To summarize the above discussion, we can say that using plain Javascript comes with the following changes:
writing step-by-step process to perform a task (imperative programming)
takes more time in rendering and re-rendering of a webpage
managing the state is extremely difficult in complex applications
less abstraction
we have to manually update the UI when the underlying data source changes
React offers a very effective solution to the above as well as a bunch of other problems. Although React offers a set of other advanced things as well, these are the basic problems with the plain JavaScript way of writing code that React overcomes.
I hope this article adds value to your knowledge of developing React apps. Please feel free to leave a comment if you find anything that needs to be improved. Happy Coding!
[References: ]
[1] From JavaScript to React
[2] ReactJS Data Binding