React is a Javascript Library for building user interfaces. Now two things are important, one is Javascript Library, another is user interfaces. Library is some collection of code, which we can reuse to make our application. By using React and some collection of code, we can make our web application, mobile, desktop application and user interface.
Whenever we talk about an application, it basically has two parts. One is the frontend (ie the user interface), the other is the backend, where all the logic resides.
The frontend is the part where the user interacts, such as browsing, clicking buttons, submitting forms, etc. Then our frontend responds to it with backend.
And the backend contains a lot of complex logic and data, such as authentication, authorization, data manipulation, etc.
But React is not concerned at all with the backend. React only works with the user interface.
Now if we talk about the web, we know that Javascript is the default programming language of the browser. But React is not a programming language, it's just a Javascript library.
That means, everything we do in React is ultimately nothing more than pure vanilla Javascript.
Well, let me ask you a question. React came in 2013 bro, so didn't we make user interface before that?
Yes, we've done this before with pure Javascript and jQuery.
Now the question is, why React came again? What would be the problem with Javascript?
To understand what problem React actually comes to solve, we need to dig a little deeper. Let's take a deep dive...!
We will see with a small application. We will create a small counter application, as you can see below, a simple HTML code with two ids named counterNumber and button.
Now take a look at the JavaScript code image, there is a simple code. I don't intend to explain this code to you. Pay attention to what I mean.
counterNumber and button are selected as DOM Elements, then the count value is incremented by 1 with addEventListener. Then the value of counterNumberEl is updated there. What is really going on here? If you look carefully, you will understand that there are basically two functions:
1. Grabbing the Elements and working with them is what we want to do.
2. Updating the UI (User Interface)
So, what's the problem here? The code is working! However, suppose you need two counter applications. What to do then?
You need to go back to that HTML and grab a new div, grab it separately with the new ids. Then the UI should be updated later.
Now, I'm only talking about two counter applications, but when there are too many interactions and complex UIs, developers will be overwhelmed. This is the main problem! You are creating functionality on one hand, and on the other hand updating the UI, which becomes very painful.
When a company like Facebook faced this huge problem, Jordan Walke, a Facebook software engineer, created React.js in 2011, inspired by PHP's Component Based Framework XHP-js. It was first implemented in Facebook's newsfeed in 2011, and in 2012 it was used in Instagram. Open sourced React.js in 2013.
Now we know why we use React. So let's do the counter application that we did with vanilla JS now using React. Then your confidence will increase that how much easier the life of developers has become after React. Let's go to the code…
First of all, I will show you how to install React for your convenience, but no one uses React in this way in our project. I am only showing it like this for the convenience of understanding so that you can understand it from the core level.
Here I just connected React with this link as they say from react.org site. Now if I go to the react.js file and write console.log(React) and console.log(ReactDOM), then we can see 2 objects in the console, that means our React is connected. Notice, there is nothing but an empty div inside the body tag, just an id called root.
In JavaScript, we can create elements in the DOM in the same way that we first worked with selectors. Similarly we can create elements in React as well. Here a div is created, inside it is printed Hello World with p tag. While this doesn't seem like a problem at the moment, when you create too many elements, life is over! Doing the same thing over and over again is a problem. That's why React created its own markup, called JSX (JavaScript XML). Although it looks like HTML, it's actually JSX.
This is how it is written in the image above. But the thing is, the browser won't understand this JSX. So to solve this problem comes our transpiler Babel, which will transpile our JSX into vanilla JS, which the browser will understand.
To connect Babel visit our website > Setup > Copy this link below the body tag of my HTML and js file we have I made type=”text/babel” there.
Now since it's JSX, we can write whatever JavaScript we want here. So let's simplify this syntax. First let's put it into a JS function.
Note here, myElement tare I just put in a function called Increment and making the Increment function like this makes it easier to write in React. Now we can write the JS here, if we had worked with the previous JS code here, it would have worked. But React says that if you want to manage state the way I do, you don't have to think about UI updates. So in React they provide a function called useState, I am showing how to use it.
This useState will serve as the state of our increment button. UseState defaults to a value, which will show the default in our state, in this case we have to give 0. The useState function basically returns us an array, which contains 2 things — one is the value we're giving, and the other is a function that updates the state value. So now we have separated the array by destructuring it.
Now if we want counter as our initial value, now after return we can give {counter} like this instead of 0. This is called interpolation. Now the value of the counter will change dynamically. And in the button onClick (since it is JSX, so it should be written following camelcase like onClick) should be called a functionality.
If I give it like this, then it is done, but there is a problem here. If I call the setCounter function like this, it will be already called, which we don't want. We want the button's value to increment when someone clicks on it. So we need to make an anonymous arrow function, then the problem will be solved.
Now if you notice that here we didn't manually update the UI by grabbing any element of the DOM, here we just told React what we want, the rest React updated the UI itself.
Now when we gave the JS example, the major problem we had with JS was — having to manually update the UI. If we wanted to use the application again, we would have to do the same thing again and again.
But React solves both these problems. We have seen how React works without manually updating the UI, now we will see how React helps us if we need to use this application in 2-3 places.
Look here, I just <>> In this, I am calling the increment function 2 times, the work is done. Now the most interesting thing is that you can run 2 applications separately, which means they will manage state separately. I mean you understand, you can use it anywhere on the whole website if you want, but again different places will be different, meaning one is not related to another. This is the power of Reactjs.
Basically, you tell React what your functionality will be, and React will automatically update the UI accordingly. This is the beauty of ReactJS.
So what are we talking about React? Why do we use React? Now I fully understand what problem React came to solve. No more such questions can hold you back in the interview board. It is not an easy task to read completely with such patience, brother. You've done it, good luck to you.
Happy Coding!
The above is the detailed content of What is React and How it works ?. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











PlacingtagsatthebottomofablogpostorwebpageservespracticalpurposesforSEO,userexperience,anddesign.1.IthelpswithSEObyallowingsearchenginestoaccesskeyword-relevanttagswithoutclutteringthemaincontent.2.Itimprovesuserexperiencebykeepingthefocusonthearticl

The following points should be noted when processing dates and time in JavaScript: 1. There are many ways to create Date objects. It is recommended to use ISO format strings to ensure compatibility; 2. Get and set time information can be obtained and set methods, and note that the month starts from 0; 3. Manually formatting dates requires strings, and third-party libraries can also be used; 4. It is recommended to use libraries that support time zones, such as Luxon. Mastering these key points can effectively avoid common mistakes.

Event capture and bubble are two stages of event propagation in DOM. Capture is from the top layer to the target element, and bubble is from the target element to the top layer. 1. Event capture is implemented by setting the useCapture parameter of addEventListener to true; 2. Event bubble is the default behavior, useCapture is set to false or omitted; 3. Event propagation can be used to prevent event propagation; 4. Event bubbling supports event delegation to improve dynamic content processing efficiency; 5. Capture can be used to intercept events in advance, such as logging or error processing. Understanding these two phases helps to accurately control the timing and how JavaScript responds to user operations.

If JavaScript applications load slowly and have poor performance, the problem is that the payload is too large. Solutions include: 1. Use code splitting (CodeSplitting), split the large bundle into multiple small files through React.lazy() or build tools, and load it as needed to reduce the first download; 2. Remove unused code (TreeShaking), use the ES6 module mechanism to clear "dead code" to ensure that the introduced libraries support this feature; 3. Compress and merge resource files, enable Gzip/Brotli and Terser to compress JS, reasonably merge files and optimize static resources; 4. Replace heavy-duty dependencies and choose lightweight libraries such as day.js and fetch

The main difference between ES module and CommonJS is the loading method and usage scenario. 1.CommonJS is synchronously loaded, suitable for Node.js server-side environment; 2.ES module is asynchronously loaded, suitable for network environments such as browsers; 3. Syntax, ES module uses import/export and must be located in the top-level scope, while CommonJS uses require/module.exports, which can be called dynamically at runtime; 4.CommonJS is widely used in old versions of Node.js and libraries that rely on it such as Express, while ES modules are suitable for modern front-end frameworks and Node.jsv14; 5. Although it can be mixed, it can easily cause problems.

There are three common ways to initiate HTTP requests in Node.js: use built-in modules, axios, and node-fetch. 1. Use the built-in http/https module without dependencies, which is suitable for basic scenarios, but requires manual processing of data stitching and error monitoring, such as using https.get() to obtain data or send POST requests through .write(); 2.axios is a third-party library based on Promise. It has concise syntax and powerful functions, supports async/await, automatic JSON conversion, interceptor, etc. It is recommended to simplify asynchronous request operations; 3.node-fetch provides a style similar to browser fetch, based on Promise and simple syntax

JavaScript's garbage collection mechanism automatically manages memory through a tag-clearing algorithm to reduce the risk of memory leakage. The engine traverses and marks the active object from the root object, and unmarked is treated as garbage and cleared. For example, when the object is no longer referenced (such as setting the variable to null), it will be released in the next round of recycling. Common causes of memory leaks include: ① Uncleared timers or event listeners; ② References to external variables in closures; ③ Global variables continue to hold a large amount of data. The V8 engine optimizes recycling efficiency through strategies such as generational recycling, incremental marking, parallel/concurrent recycling, and reduces the main thread blocking time. During development, unnecessary global references should be avoided and object associations should be promptly decorated to improve performance and stability.

The difference between var, let and const is scope, promotion and repeated declarations. 1.var is the function scope, with variable promotion, allowing repeated declarations; 2.let is the block-level scope, with temporary dead zones, and repeated declarations are not allowed; 3.const is also the block-level scope, and must be assigned immediately, and cannot be reassigned, but the internal value of the reference type can be modified. Use const first, use let when changing variables, and avoid using var.
