Íme néhány ok, amiért a React olyan gyorsan népszerűvé vált:
- A DOM API-val nehéz dolgozni. A React alapvetően lehetőséget nyújt a fejlesztőknek arra, hogy egy virtuális böngészővel dolgozzanak, amely barátságosabb, mint a valódi böngésző. A React virtuális böngészője ügynökként viselkedik a fejlesztő és a valódi böngésző között.
- A React lehetővé teszi a fejlesztők számára, hogy deklaratív módon leírják felhasználói interfészeiket, és modellezzék az interfészek állapotát. Ez azt jelenti, hogy a fejlesztők az interfészek tranzakcióinak leírására szolgáló lépések helyett csak a végső állapot (például egy függvény) szempontjából írják le a felületeket. Amikor tranzakciók történnek az adott állapottal, a React gondoskodik a felhasználói felületek frissítéséről ez alapján.
- A React csak JavaScript, egy nagyon kicsi API-val lehet megtanulni, csak néhány funkció és azok használata. Ezt követően a JavaScript képességeid teszik jobb React fejlesztővé. A belépésnek nincsenek akadályai. A JavaScript fejlesztőből néhány óra alatt produktív React fejlesztővé válhat.
De ennél sokkal többről van szó. Próbáljunk kitérni a React növekvő népszerűségének összes okára. Ennek egyik oka a virtuális DOM (a React egyeztetési algoritmusa). Kidolgozunk egy példát, amely megmutatja az ilyen algoritmus parancsának tényleges értékét.
A React hivatalos meghatározása szerint ez egy JavaScript könyvtár a felhasználói felületek felépítéséhez . Fontos megérteni a meghatározás két különböző részét:
- A React egy JavaScript könyvtár . Ez nem keret. Ez nem teljes megoldás, és a megoldás kialakításához gyakran több könyvtárat kell használnunk a React alkalmazással. A React semmilyen teljes megoldásnál nem feltételez semmit a többi részről. Csak egy dologra összpontosít, és arra, hogy ezt a dolgot nagyon jól csinálja.
- Az a dolog, amit a React igazán jól csinál, a definíció második része: Felhasználói felületek felépítése . A felhasználói felület bármi, amit a felhasználók elé állítunk, hogy kölcsönhatásba léphessenek egy géppel. A felhasználói interfészek mindenhol megtalálhatók, a mikrohullámú sütő egyszerű gombjaitól az űrsikló műszerfaláig. Ha a kezelőfelületünkkel próbálkozó eszköz megérti a JavaScript-et, akkor a React segítségével leírhatjuk a felhasználói felületet.
Mivel a webböngészők értik a JavaScript-et, a React használatával leírhatjuk a webes felhasználói felületeket. Szeretem használni a szót leírni ide, mert ez az, amit mi alapvetően köze reagál, csak mondd meg, hogy mit akarunk, és reagálni fog építeni a tényleges felhasználói interfészek, a nevünkben, a webböngészőben. A React vagy hasonló könyvtárak nélkül manuálisan kell létrehoznunk felhasználói felületeket natív webes API-kkal és JavaScript-sel.
Amikor meghallja azt a kijelentést, hogy a „React deklaratív”, ez pontosan ezt jelenti, leírjuk a felhasználói interfészeket a React-tel, és elmondjuk neki, hogy mit akarunk (nem pedig azt, hogyan kell csinálni). A React gondoskodik a „hogyanról” és lefordítja a deklaratív leírásokat (amelyeket a React nyelven írunk) a böngésző tényleges felhasználói felületeire. A React megosztja ezt az egyszerű kijelentő erőt magával a HTML-lel, de a React-tel deklaratívak leszünk a HTML-interfészek számára, amelyek dinamikus adatokat képviselnek, nem csak statikus adatokat.
A React három fő tervezési koncepcióval rendelkezik, amelyek ösztönzik a népszerűségét:
1 - Újrafelhasználható, összeállítható és állapotjelző elemek használata
A React-ben komponensek segítségével írjuk le a felhasználói interfészeket. Az összetevőket egyszerű funkcióknak tekintheti (bármilyen programozási nyelven). Hívunk függvényeket valamilyen bemenettel, és ezek kimenetet adnak nekünk. Szükség szerint újrafelhasználhatjuk a függvényeket, és kisebbekből nagyobb funkciókat állíthatunk össze.
Az alkatrészek pontosan megegyeznek; "tulajdonságoknak" és "állapotnak" nevezzük a bemenetüket, és egy összetevő kimenet egy felhasználói felület leírása (amely hasonló a böngészők HTML-jéhez). Egyetlen összetevőt több felhasználói felületen is felhasználhatunk, és az összetevők más összetevőket is tartalmazhatnak.
A tiszta függvényektől eltérően a teljes React komponensnek lehet privát állapota az adatok tárolásához, amelyek idővel változhatnak.
2 - A reaktív frissítések jellege
React neve az egyszerű magyarázat erre a koncepcióra. Amikor egy alkatrész (a bemenet) állapota megváltozik, az általa képviselt felhasználói felület (a kimenet) is megváltozik. A felhasználói felület leírásának ezt a változást tükröznie kell abban az eszközben, amellyel dolgozunk.
Egy böngészőben regenerálnunk kell a HTML nézeteket a Document Object Model (DOM) dokumentumban. A React használatakor nem kell aggódnunk, hogy miként tükrözhetjük ezeket a változásokat, sőt nem kell kezelnünk , hogy mikor kell változtatni a böngészőben; A React egyszerűen reagál az állapotváltozásokra, és szükség esetén automatikusan frissíti a DOM-ot.
3 - A nézetek virtuális ábrázolása a memóriában
A React segítségével HTML-t írunk JavaScript használatával. Bizonyos adatokon alapuló HTML előállításához a JavaScript erejére támaszkodunk, ahelyett, hogy továbbfejlesztenénk a HTML-t, hogy működjön együtt az adatokkal. A HTML javításával általában más JavaScript keretrendszerek foglalkoznak. Például az Angular kiterjeszti a HTML-t olyan funkciókkal, mint a hurkok, a feltételek és egyéb.
Amikor csak az adatokat kapjuk a szerverről (a háttérben, AJAX-szal), a HTML-nél többre van szükségünk az adatok kezeléséhez. Vagy továbbfejlesztett HTML-t használ, vagy maga a JavaScript erejét használja a HTML létrehozásához. Mindkét megközelítésnek vannak előnyei és hátrányai. A React átfogja az utóbbit azzal az érvvel, hogy az előnyök erősebbek, mint a hátrányok.
Valójában van egy fő előny, amely önmagában is érvényesítheti ezt a megközelítést; A HTML rendereléséhez a JavaScript használata megkönnyíti a React számára a HTML virtuális reprezentációjának megőrzését a memóriában (amelyet általában a The Virtual DOM néven ismerünk ). A React a virtuális DOM-ot használja először egy HTML fa megjelenítéséhez, majd minden alkalommal, amikor egy állapot megváltozik, és kapunk egy új HTML fát, amelyet el kell vinni a böngésző DOM-jába, ahelyett, hogy az egész új fát írnánk, a React csak a különbség az új fa és az előző fa között (mivel a React-nek mindkét fája a memóriában van). Ez a folyamat faegyeztetés néven ismert , és szerintem ez a legjobb dolog, ami az AJAX óta történt a webfejlesztésben!
A következő példában erre az utolsó koncepcióra fogunk összpontosítani, és egy egyszerű gyakorlati példát mutatunk be a faegyeztetési folyamatról és az általa okozott nagy különbségről. Kétszer is megírjuk ugyanazt a HTML-példát, először natív webes API-kat és vanília JavaScriptet használva, majd meglátjuk, hogyan lehet leírni ugyanazt a HTML-fát a React segítségével.
Annak érdekében, hogy pusztán erre az utolsó koncepcióra összpontosítsunk, nem használunk összetevőket, és egy állapotváltoztatási műveletet gúnyolunk egy JavaScript időzítő segítségével. Ugyancsak nem fogjuk használni a JSX-t, bár a JSX használata sokkal egyszerűbb kódot eredményez. A React írásakor folyamatosan használom a JSX-t, de ebben a példában közvetlenül a React API-val dolgozva remélhetőleg sokkal jobban meg fogja érteni ezt a koncepciót.
React egyeztetési algoritmusa
A példa követéséhez böngészőre és kódszerkesztőre van szükség. Valójában használhat online kódoló játszóteret, de a helyi fájlokat használom, és közvetlenül egy böngészőben tesztelem őket (nincs szükségünk webszerverre):
Ezt a példát a semmiből kezdjük. Hozzon létre egy új könyvtárat, és indítsa el ott kedvenc szerkesztőjét:
mkdir react-democd react-demoatom .
Hozzon létre egy index.html
fájlt abban a könyvtárban, és tegyen egy szabványos HTML sablont. Helyezzen be a sablonba egy script.js
fájlt, és tegyen egy console.log
utasítást a szkriptbe annak tesztelésére, hogy az include működik:
React Demo
Nyissa meg a index.html
fájlt a böngészőjében, és győződjön meg arról, hogy problémamentesen látja az üres sablont, és hogy a Konzol fejlesztői eszközei lapon láthatja a console.log
tesztüzenetet script.js
:
open index.html # On Mac explorer index.html # On Windows
Now, let’s bring in the React library itself, which we can include from the Reactjs website. Copy both the react
and react-dom
scripts, and include them in index.html
:
We’re including two different scripts here for an important reason: The React
library itself can be used without a browser. To use React with a browser, we need the ReactDOM
library.
When we refresh the browser now, we should see both React
and ReactDOM
available on the global scope:

With this simple setup, we can now access both React
and ReactDOM
APIs, and of course, we also have access to the native Web APIs and JavaScript which we are going to use first.
To insert HTML dynamically in the browser we can simply use pure JavaScript and the DOM Web API itself. Let’s create a div
element to host our JavaScript HTML content and give it the id "js"
. In the body element of index.html
, right before the script
tag, add:
Now in script.js
, let's grab this new div
element by its id and put it in a constant. Let's name this constant jsContainer
. We can use document.getElementById
to grab the div
from HTML:
jsContainer.innerHTML = ` Hello JS `;
To control the content of this div
, we can use the innerHTML
setter call on the div
element directly. We can use this call to supply any HTML template that we want inserted in the DOM. Let's insert a div
element with a class of "demo" and the string "Hello JS" as its content:
jsContainer.innerHTML = ` Hello JS `;ReactDOM.render( /* TODO: React's version of the HTML template */, reactContainer )
Make sure this works in the browser. You should see the “Hello JS” line on the screen now.
This demo div is our User Interface so far. It’s a very simple one. We just output a text for the user to see.
Both document.getElementById
and element.innerHTML
are actually part of the native DOM Web API. We are communicating with the browser directly here using the supported APIs of the Web platform. When we write React code, however, we use the React API instead, and we let React communicate with the browser using the DOM Web API.
React acts like our agent for the browser, and we mostly need to communicate with just React, our agent, and not the browser itself. I say mostly because there are cases where we still need to communicate with the browser, but those are rare.
To create the exact same User Interface that we have so far but with React API this time, let’s create another div
element and give it an id of "react"
. In index.html
, right under the div#js
element, add:
Now, in script.js
, create a new container constant for the new div
:
const reactContainer = document.getElementById("react");
This container will be the only call we make to the native web API. ReactDOM needs this container to know where to host our application in the DOM.
With the react container identified, we can now use the ReactDOM library to render
React's version of the HTML template to this container:
ReactDOM.render( /* TODO: React's version of the HTML template */, reactContainer )
What we’re going to do next is your first milestone in truly understanding the React library. Remember when I told you that with React we write HTML using JavaScript? This is exactly what we are going to do next.
To write our simple HTML User Interface, we are going to use JavaScript calls to React API, and by the end of the example you’ll have a better picture about the reason for doing so.
Instead of working with strings (as we did in the native JavaScript example above), in React, we work with objects. Any HTML string will be represented as an object using a React.createElement
call (which is the core function in the React API).
Here’s the equivalent HTML User Interface we have so far with React:
ReactDOM.render( React.createElement( "div", { className: "demo" }, "Hello React" ), reactContainer );
React.createElement
has many arguments:
- The first argument is the HTML tag, which is
div
in our example. - The second argument is an object that represents any attributes we want this tag to have. To match the native JS example we used
{ className: "demo" }
which translates toclass="demo"
. Note how we usedclassName
instead ofclass
in the attributes because with React it's all JavaScript that matches the Web API, not HTML itself. - The third argument is the content of the element. We’ve put a “Hello React” string in there.
We can test this now. The browser should render both “Hello JS” and “Hello React”. Let’s style the demo divs as a box, using this CSS, just so that we can visually split the screen. In index.html
:
.demo { border: 1px solid #ccc; margin: 1em; padding: 1em; }

We now have two nodes, one being controlled with the DOM Web API directly, and another being controlled with the React API (which in turn uses the DOM Web API). The only major difference between the ways we are building these two nodes in the browser is that in the JS version we used a string to represent the content, while in the React version we used pure JavaScript calls and represented the content with an object instead of a string.
No matter how complicated the HTML User Interface is going to get, when using React, every HTML element will be represented with a JavaScript object using a React.createElement
call.
Let’s now add some more features to our simple User Interface. Let’s add a text box to read input from the user.
To nest elements in our HTML template, it’s straight forward in the JS version because it’s just HTML. For example, to make the demo div
render an element, we simply add it to the content:
jsContainer.innerHTML = ` Hello JS `;
We can do the same with React by adding more arguments after the 3rd argument for React.createElement
. To match what we did in the native JS example, we can add a 4th argument that is another React.createElement
call that renders an input
element (remember, every HTML element is an object):
ReactDOM.render( React.createElement( "div", { className: "demo" }, "Hello React", React.createElement("input") ), reactContainer );
At this point, if you’re questioning what we’re doing and thinking “this is complicating a simple process”, you are totally right! But there is a very good reason for what we’re doing. Keep reading.
Let’s also render a timestamp in both versions. In the JS version, let’s put the timestamp in a paragraph element. We can use a call to new Date()
to display a simple timestamp:
jsContainer.innerHTML = ` Hello JS ${new Date()}
`;
To do the same in React, we add a 5th argument to the top-level div
element. This new 5th argument is another React.createElement
call, this time using a p
tag, with no attributes, and the new Date()
string for content:
ReactDOM.render( React.createElement( "div", { className: "demo" }, "Hello React", React.createElement("input"), React.createElement( "p", null, new Date().toString() ) ), reactContainer );
Both JS and React versions are still rendering the exact same HTML in the browser.

As you can see, so far, using React is actually a lot harder than the simple and familiar native way. What is it that React does so well that’s worth giving up the familiar HTML and having to learn a new API to write what can be simply written in HTML? The answer is not about rendering the first HTML view, it’s about what we need to do to update any existing view in the DOM.
So, let’s do an update operation on the DOM we have so far. Let’s simply make the timestamp tick every second.
We can easily repeat a JavaScript function call in a browser using the setInterval
Web timer API. So, let's put all of our DOM manipulations for both JS and React versions in a function, call it render
, and use it in a setInterval
call to make it repeat every second.
Here’s the full final code in script.js
:
const jsContainer = document.getElementById("js"); const reactContainer = document.getElementById("react"); const render = () => { jsContainer.innerHTML = ` Hello JS ${new Date()}
`; ReactDOM.render( React.createElement( "div", { className: "demo" }, "Hello React ", React.createElement("input"), React.createElement( "p", null, new Date().toString() ) ), reactContainer ); } setInterval(render, 1000);
When we refresh the browser now, the timestamp string should be ticking every second in both versions. We are now updating our User Interface in the DOM.
This is the moment when React will potentially blow your mind. If you try to type something in the text box of the JS version, you won’t be able to. This is very much expected because we’re basically throwing away the whole DOM node on every tick and regenerating it. However, if you try to type something in the text box that’s rendered with React, you can certainly do so!
Although the whole React rendering code is within our ticking timer, React is changing only the timestamp paragraph and not the whole DOM node. This is why the text input box was not regenerated and we were able to type in it.
You can see the different ways we’re updating the DOM visually if you inspect the two DOM nodes in a Chrome dev tools elements panel. The Chrome div tools highlights any HTML elements that get updated. You’ll see how we are regenerating the whole “js” div on every tick, while React is smartly only regenerating the paragraph with the timestamp string.

React has a smart diffing algorithm that it uses to only regenerate in its DOM node what actually needs to be regenerated while it keeps everything else as is. This diffing process is possible because of React’s virtual DOM and the fact that we have a representation of our User Interface in memory (because we wrote in JavaScript).
Using the virtual DOM, React keeps the last DOM version in memory and when it has a new DOM version to take to the browser, that new DOM version will also be in memory, so React can compute the difference between the new and the old versions (in our case, the difference is the timestamp paragraph).
React will then instruct the browser to update only the computed diff and not the whole DOM node. No matter how many times we regenerate our interface, React will take to the browser only the new “partial” updates.
Not only is this method a lot more efficient, but it also removes a big layer of complexity for the way we think about updating User Interfaces. Having React do all the computations about whether we should update the DOM or not enables us to focus on thinking about our data (state) and the way to describe a User Interface for it.
We then manage the updates on our data as needed without worrying about the steps needed to reflect these updates on the actual User Interface in the browser (because we know React will do exactly that and it will do that in an efficient way!)
Thanks for reading! You can view the source code of my demo here, and you can see the demo running here.
Learning React or Node? Checkout my books:
- Learn React.js by Building Games
- Node.js Beyond the Basics