What exactly is React.js?
--
In the simple and popular term, React is the V (View) in MVC (Model/View/Controller).
In more descriptive terms, React is a JavaScript library (from Facebook) that is used to render views (for example, HTML pages) dynamically based on some state, which is often in the form of data. React then updates the generated views whenever the original state changes. React is a small but powerful library, with the power being more in the concepts than in the implementation.
Some of the concepts under which React operates:
Reusable, composable, and stateful components:
In React, we build HTML views using smaller components. We can reuse a single component in multiple places, with different state and properties, and every component can contain other components. All components in React have a state that may change over time, and React will take care of updating the components’ views when their state changes.
The nature of reactive updates:
React’s name is the simple explanation for this concept. When the state of a component changes, those changes need to be reflected somewhere, for example, if we’re writing HTML components for a browser, we need to regenerate the HTML for the browser’s DOM (Document Object Model). With React, we do not have to worry about how to reflect the state changes, React will simply react to the changes and update views as needed.
The virtual representation of views in memory:
For the browser’s case, we write HTML using JavaScript in React relying on the power of JavaScript to generate HTML that depends on some data, rather than enhancing HTML to make it work with that data. Enhancing HTML is what other JavaScript frameworks usually do (for example, Angular.js extends HTML with features like loops, conditionals, and others).
If we are receiving just the data from the server (with AJAX), we need something more than HTML to work with it, so it’s either using an enhanced HTML, or just using the power of JavaScript itself to generate the HTML. Each of these approaches has advantages and disadvantages, and React embraces the latter one, with the argument that the advantages are stronger than the disadvantages, and I, of course, agree.
Using JavaScript to render HTML allows React to have a virtual representation of HTML in memory (which is aptly named, the Virtual DOM), and React uses that to rerender the views virtually first. Every time a state changes, and we have a new HTML tree that needs to be written back to the browser’s DOM, instead of writing the whole tree, React will only write the difference between the new tree and the previous tree (since React has both trees in memory). This process is known as Tree Reconciliation, and I think, it is the best thing that happened to Web Development since AJAX!
Samer Buna is the author of “React.js: Getting Started”, “Building Data-driven React Applications with Relay, GraphQL, and Flux” and multiple other courses on Pluralsight.