הנה כמה סיבות מדוע ריאקט הפך כל כך פופולרי כל כך מהר:
- העבודה עם ממשק ה- API של DOM קשה. תגובה מגדירה בעצם למפתחים את היכולת לעבוד עם דפדפן וירטואלי ידידותי יותר מהדפדפן האמיתי. הדפדפן הווירטואלי של React מתנהג כמו סוכן בין המפתח לדפדפן האמיתי.
- React מאפשר למפתחים לתאר באופן הצהרתי את ממשקי המשתמשים שלהם ולדגם את מצב הממשקים הללו. משמעות הדבר היא במקום לבוא עם צעדים לתיאור עסקאות בממשקים, מפתחים פשוט מתארים את הממשקים במונחים של מצב סופי (כמו פונקציה). כאשר עסקאות קורות למצב זה, React דואגת לעדכן את ממשקי המשתמש על סמך זה.
- תגובה היא רק JavaScript, יש ממשק API קטן מאוד ללמוד, רק כמה פונקציות וכיצד להשתמש בהן. לאחר מכן, כישורי JavaScript שלך הם שהופכים אותך למפתח תגובה טוב יותר. אין חסמי כניסה. מפתח JavaScript יכול להפוך למפתח React יצרני תוך מספר שעות.
אבל יש בזה הרבה יותר מסתם זה. בואו ננסה לכסות את כל הסיבות העומדות מאחורי הפופולריות הגואה של ריאקט. אחת הסיבות היא ה- DOM הווירטואלי שלו (אלגוריתם הפיוס של React). אנו נעבור דוגמה כדי להראות את הערך המעשי בפועל שיש אלגוריתם כזה בפקודתך.
ההגדרה הרשמית של React קובעת שמדובר בספריית JavaScript לבניית ממשקי משתמש . חשוב להבין את שני החלקים השונים של הגדרה זו:
- תגובה היא ספריית JavaScript . זו לא מסגרת. זה לא פתרון מלא ולעתים קרובות נצטרך להשתמש בספריות נוספות עם React כדי ליצור פתרון כלשהו. תגובה אינה מניחה דבר לגבי החלקים האחרים בשום פתרון מלא. זה מתמקד רק בדבר אחד, ובעשייה טובה מאוד של הדבר הזה.
- הדבר ש- React עושה ממש טוב הוא החלק השני של ההגדרה: בניית ממשקי משתמש . ממשק משתמש הוא כל מה שאנחנו מציבים בפני המשתמשים כדי שיוכלו לקיים אינטראקציה עם מכונה. ממשקי משתמש נמצאים בכל מקום, החל מהכפתורים הפשוטים במיקרוגל ועד לוח המחוונים של מעבורת חלל. אם המכשיר שאנו מנסים לממשק יכול להבין JavaScript, נוכל להשתמש ב- React כדי לתאר ממשק משתמש עבורו.
מכיוון שדפדפני אינטרנט מבינים JavaScript, אנו יכולים להשתמש ב- React לתיאור ממשקי משתמש באינטרנט. אני אוהב להשתמש במילה המתוארת כאן מכיוון שזה מה שאנחנו בעצם עושים עם React, אנחנו פשוט אומרים לו מה שאנחנו רוצים ו- React יבנה את ממשקי המשתמש בפועל, מטעמנו, בדפדפן האינטרנט. ללא ספריות React או דומות, נצטרך לבנות באופן ידני ממשקי משתמש עם ממשקי API מקומיים ו- JavaScript.
כשאתה שומע את ההצהרה ש- "תגובה היא הצהרתית", זה בדיוק המשמעות של זה, אנו מתארים ממשקי משתמש עם תגובה ואומרים לו מה אנו רוצים (לא כיצד לעשות זאת). React ידאג ל"איך "ויתרגם את התיאורים ההצהרתיים שלנו (אותם אנו כותבים בשפת React) לממשקי משתמש בפועל בדפדפן. ריאקט חולק את העוצמה ההצהרתית הפשוטה הזו עם HTML עצמו, אך עם תגובה, אנו צריכים להיות הצהרתיים לממשקי HTML המייצגים נתונים דינמיים, ולא רק נתונים סטטיים.
ל- React שלושה מושגי עיצוב עיקריים המניעים את הפופולריות שלה:
1 - שימוש ברכיבים רב פעמיים, ניתנים להלחנה ומלאי מדינה
ב- React, אנו מתארים ממשקי משתמש המשתמשים ברכיבים. אתה יכול לחשוב על רכיבים כפונקציות פשוטות (בכל שפת תכנות). אנו קוראים לפונקציות עם קלט כלשהו והן נותנות לנו קצת פלט. אנו יכולים לעשות שימוש חוזר בפונקציות לפי הצורך ולהרכיב פונקציות גדולות יותר מפונקציות קטנות יותר.
הרכיבים זהים לחלוטין; אנו מכנים את הקלט שלהם "מאפיינים" ו"מצב ", ופלט רכיבים הוא תיאור של ממשק משתמש (הדומה ל- HTML לדפדפנים). אנו יכולים לעשות שימוש חוזר ברכיב יחיד במספר ממשקי משתמש, ורכיבים יכולים להכיל רכיבים אחרים.
שלא כמו בפונקציות טהורות, עם זאת, רכיב React מלא יכול לקבל מדינה פרטית להחזיק נתונים שעשויים להשתנות עם הזמן.
2 - אופי העדכונים המגיבים
שמו של תגובה הוא ההסבר הפשוט למושג זה. כשמצב הרכיב (הקלט) משתנה, משתנה גם ממשק המשתמש שהוא מייצג (הפלט). שינוי זה בתיאור ממשק המשתמש צריך לבוא לידי ביטוי במכשיר שאיתו אנו עובדים.
בדפדפן, עלינו ליצור מחדש את תצוגות ה- HTML במודל אובייקט המסמך (DOM). עם React, איננו צריכים לדאוג כיצד לשקף שינויים אלה, או אפילו לנהל מתי לבצע שינויים בדפדפן; תגובה פשוט תגיב לשינויים במצב ותעדכן אוטומטית את ה- DOM בעת הצורך.
3 - ייצוג וירטואלי של השקפות בזיכרון
עם React אנו כותבים HTML באמצעות JavaScript. אנו מסתמכים על כוחו של JavaScript ליצור HTML התלוי בנתונים מסוימים, במקום לשפר את ה- HTML כדי לגרום לו לעבוד עם נתונים אלה. שיפור HTML הוא מה שמסגרות JavaScript אחרות עושות בדרך כלל. לדוגמה, Angular מרחיב HTML עם תכונות כמו לולאות, תנאים ואחרים.
כאשר אנו מקבלים רק את הנתונים מהשרת (ברקע, עם AJAX), אנו זקוקים למשהו יותר מ- HTML כדי לעבוד עם הנתונים הללו. זה באמצעות HTML משופר, או באמצעות הכוח של JavaScript עצמו ליצירת ה- HTML. לשתי הגישות יתרונות וחסרונות. תגובה מחבקת את האחרונה עם הטענה כי היתרונות חזקים מהחסרונות.
לאמיתו של דבר, ישנו יתרון מרכזי אחד שיכול להכריע את הגישה הזו בפני עצמה; שימוש ב- JavaScript כדי לעבד HTML מקל על React לשמור על ייצוג וירטואלי של HTML בזיכרון (הידוע בכינויו The Virtual DOM ). React משתמש ב- DOM הווירטואלי כדי לעבד עץ HTML כמעט קודם, ואז, בכל פעם שמצב משתנה ואנחנו מקבלים עץ HTML חדש שצריך לקחת ל- DOM של הדפדפן, במקום לכתוב את כל העץ החדש React רק יכתוב את ה- ההבדל בין העץ החדש לעץ הקודם (מכיוון של- React יש את שני העצים בזיכרון). תהליך זה ידוע בתור התאמת עצים , ואני חושב שזה הדבר הכי טוב שקרה בפיתוח אתרים מאז AJAX!
בדוגמה הבאה נתמקד בתפיסה האחרונה הזו ונראה דוגמה מעשית פשוטה לתהליך פיוס העץ ולהבדל הגדול שהוא עושה. נכתוב את אותה דוגמת HTML פעמיים, תחילה באמצעות ממשקי API מקומיים של Web ו- JavaScript וניל, ואז נראה כיצד לתאר את אותו עץ HTML בעזרת React.
כדי להתמקד אך ורק במושג אחרון זה, לא נשתמש ברכיבים ונלעוג על פעולת שינוי מצב באמצעות טיימר JavaScript. אנחנו גם לא מתכוונים להשתמש ב- JSX, אם כי השימוש ב- JSX יהווה קוד פשוט בהרבה. אני משתמש ב- JSX כל הזמן כשאני כותב React, אך עבודה עם React API ישירות בדוגמה זו תקווה שתבין את המושג הזה הרבה יותר טוב.
דוגמה לאלגוריתם של פיוס של React
כדי לבצע דוגמה זו, דרוש לך דפדפן ועורך קוד. אתה יכול למעשה להשתמש במגרש משחקים מקוון מקוון, אך אשתמש בקבצים מקומיים ואבדוק אותם ישירות בדפדפן (איננו זקוקים לשרת אינטרנט):
נתחיל את הדוגמה הזו מאפס. צור ספריה חדשה והפעל שם את העורך המועדף עליך:
mkdir react-democd react-demoatom .
צור index.html
קובץ בספרייה זו ושם שם תבנית HTML רגילה. כלול בתבנית זו script.js
קובץ והוסף console.log
הצהרה בתסריט זה כדי לבדוק שהכלול עובד:
React Demo
פתח את index.html
הקובץ בדפדפן שלך וודא שאתה יכול לראות את התבנית הריקה ללא בעיות, וכי אתה יכול לראות בכרטיסיית כלי העיצוב של המסוף את console.log
הודעת הבדיקה שהכנסת script.js
:
open index.html # On Mac explorer index.html # On Windows
עכשיו, בואו נביא את ספריית ה- React עצמה, אותה נוכל לכלול מאתר Reactjs. העתק את התסריטים react
ואת react-dom
הסקריפטים, והכלל אותם ב index.html
:
אנו כוללים שני סקריפטים שונים מסיבה חשובה: React
ניתן להשתמש בספרייה עצמה ללא דפדפן. כדי להשתמש ב- React עם דפדפן, אנו זקוקים ReactDOM
לספרייה.
כשאנו לרענן את הדפדפן עכשיו, אנחנו צריכים לראות את השנייה React
ו ReactDOM
זמינים על ההיקף הגלובלי:

עם התקנה פשוט זו, אנו יכולים כעת גישה היא React
ו ReactDOM
APIs, וכמובן, יש לנו גם גישת APIs האינטרנט המקומית ו- JavaScript שבו אנחנו הולכים להשתמש ראשון.
כדי להוסיף HTML באופן דינמי בדפדפן אנו יכולים פשוט להשתמש ב- JavaScript טהור וב- DOM Web API עצמו. בואו ניצור div
אלמנט לארח את תוכן ה- JavaScript שלנו ב- JavaScript וניתן לו את המזהה "js"
. במרכיב הגוף של index.html
, ממש לפני script
התג, הוסף:
עכשיו script.js
, בואו נתפוס את div
האלמנט החדש הזה בזיהוי שלו ונשים אותו בקבוע. בואו נקרא קבוע זה jsContainer
. אנו יכולים להשתמש document.getElementById
בכדי לתפוס את ה- div
HTML:
jsContainer.innerHTML = ` Hello JS `;
כדי לשלוט בתוכן זה div
, אנו יכולים להשתמש ישירות innerHTML
בשיחת הקובע על div
האלמנט. אנו יכולים להשתמש בשיחה זו כדי לספק תבנית HTML כלשהי שנרצה להכניס ל- DOM. בואו נכניס div
אלמנט עם מחלקה של "הדגמה" והמחרוזת "שלום JS" כתוכן:
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