React -Introduction to React

React Core concept, Virtual Dom and Diff algorithm, JSX, Default Props, Prop Types, Optimizing performance, Some essentials about react.

By ferenc from unplash

React Core Concept:

React is defined as a JavaScript library for building user interfaces. Let’s start by talking about the two different parts of this definition.

React is a JavaScript “library”. It is not exactly a “framework”. It is not a complete solution and you will often need to use more libraries with React to form any solution. React does not assume anything about the other parts in any solution.

Frameworks serve a great purpose, especially for young teams and startups. When working with a framework, many smart design decisions are already made for you, which gives you a clear path to focus on writing good application-level logic. However, frameworks come with some disadvantages. For experienced developers working on large codebases, these disadvantages are sometimes a deal breaker.

Frameworks are not flexible, although some claim to be. A framework usually wants you to code everything a certain way. If you try to deviate from that way, the framework usually ends up fighting you about it. Frameworks are also usually large and full of features. If you need to use only a small piece of them, you have to include the whole thing anyway. Admittedly, this point is changing today but it is still not ideal. Some frameworks are going modular, which I think is great, but I am a big fan of the pure Unix philosophy:

Write programs that do one thing and do it well. Write programs to work together.

— Doug McIlroy

React follows the Unix philosophy because it is a small library that focuses on just one thing and on doing that thing extremely well. That “one thing” is the second part of the React’s definition: Building User Interfaces.

A User Interface (UI) is anything we put in front of users to have them interact with a machine. UIs are everywhere, from the simple buttons on a microwave to the dashboard of a space shuttle. If the device we are trying to interface can understand JavaScript, we can use React to describe a UI for it. Since Web browsers understand JavaScript, we can use React to describe Web UIs.

I like to use the word describe here because that is what we basically do with React. We just tell it what we want! React will then build the actual UI, on our behalf, in the Web browser. Without React or similar libraries, we would need to manually build UIs with native Web APIs and JavaScript and that is not as easy.

When you hear the statement that “React is declarative” this is exactly what it means. We describe UIs with React and tell it what we want (not how to do it). React will take care of the “how” and translate our declarative descriptions (which we write in the React language) to actual UIs in the browser. React shares this simple declarative power with HTML itself, but with React we get to be declarative for HTML UIs that represent dynamic data, not just static data.

When React was released, there was a lot of buzz about its performance because it introduced the smart idea of a virtual DOM that can be used to reconcile the actual DOM (and we’ll talk about that in the next section).

DOM is “Document Object Model”. It’s the browsers’ programming interface for HTML (and XML) documents that treats them as tree structures. The DOM API can be used to change a document structure, style, and content.

While React’s performance is still one of the most important reasons why it is extremely popular today, I don’t classify it as the “best” thing about it. I think React was a game changer because it created a common language between developers and browsers that allows developers to declaratively describe UIs and manage actions on their state instead of actions on their DOM elements. It’s simply the language of user interface “outcomes”. Instead of coming up with steps to describe actions on interfaces, developers just describe the interfaces in terms of a “final” state (like a function). When actions happen to that state, React takes care of updating the UIs in the DOM based on that (and it does that efficiently as we’ll see next).

If someone asked you to give one reason why React is worth learning, this outcomes-based UI language is it. I call this language “the React language”.

Virtual Dom and Diff Algorithm:

img from google

Dom and the View

doc will be here

Diff Algorithm

When you design & build the UI using React, What React basically does is, React creates two copies of the real DOM. At first, when the DOM initializes, React takes a copy of it (1). When you change something, React makes another copy of it with the changes (2). Then he compares the changes between the two copies using Diff Algorithm (an algorithm that can differentiate between two things) and then only re-paints those parts on the real DOM that you have changed. Suppose, You’ve created a list of foods that you will eat today. React will make a copy of it and store it in memory.

<ul>
<li id="1"> Orange </li>
<li id="2"> Mango </li>
<li id="3"> Banana </li>
<li id="4"> Milk </li>
</>

But you’re already hungry so you’ve eaten a banana so you replaced a banana with another food named “Chocolate” in the list. React Will make a copy of that updated list too and then compare the changes. Then it will only update that list (with id=”3" ) on the DOM. ( He won’t repaint the whole DOM for this ).

img from google

JSX --> Javacript XML

JSX Stands for JavaScript XML (Extensible Markup Language). It basically allows us to write HTML in React. But it’s not actually “HTML”. So is it an HTML template language? NO. It’s actually a declarative syntax that used to express the virtual DOM. JSX gets converted to virtual DOM, which gets diffed against the real DOM that we discussed earlier. Rather than rewriting the whole DOM tree, only changes get applied & that is the reason why React is so fast! Yeah, you can also create HTML elements using React.createElement(), but that is like holding your left ear using your right hand! The syntax is also weird. Just to create a paragraph tag, you have to write :

React.createElement("p", null, "I'm Chintu Babu, holding my left ear with using my right hand. I'm THAT guy who uses calculator to calculate 6 + 9")

Rather than doing this shit, you can use JSX to get a syntactic sugar while developing your React Application. In the end, Babel actually converts JSX to React.createElement(…)and then React converts them into pure HTML elements because that’s what the browser understands !!!

// You're writting JSX ->
<button onClick={() => alert('YES')}><span>Click me</span></button>Babel Transpiled Your JSX ->
React.createElement("button", { onClick: () => alert('YES') },
React.createElement('span', {}, 'Click me'))

Babel

So now you know Babel converts all JSX code to React elements. What is Babel, actually? Babel is a toolchain / JavaScript Compiler that is mainly used to convert ECMAScript 2015+ code into a backward-compatible version of JavaScript in current and older browsers or environments. (because some browser still doesn’t support ES6). It’s also familiar as a Transpiler. Every tool that can transform syntax from one to another is called a Transpiler. It has the ability to :

  • Transform syntax. ( Like transforming JSX into React elements).
  • Polyfill features that are missing in your target environment (through a third-party polyfill such as core-js).
  • Source code transformations (code mods).

Prop Types

doc will be here

Default props

doc will be here

Performance Optimization

React is already fast because of the Diff Algorithm that it follows. But You can optimize more using the Production Build of your React app. You can follow immutable data structures because it has zero side effects. They are simpler to create, test and use. It’s easier & faster for React to track changes if you’re following an immutable pattern. You should also treat your component’s state as immutable. use setState() to change your state rather than mutating it using this. state. You should prefer functional components and React.PureComponent because it reduces the bundle size as it minifies better than classes.

You should not install dependencies that you don’t need in your project. I saw some Chintus installing React bootstrap and Material UI in their React app. It’s totally meaningless because “Material UI” itself is a huge library for styling your UI and you don’t need React Bootstrap if you’re using Material UI For it.

Quick React Concept you need to know

Img by Franco

1) It’s not a framework

React is not a framework. Angular or Ember are frameworks where some decisions are already made for us. React is just a library and we need to make all decisions by ourselves.
It focuses on helping us to build user interfaces using components.
It doesn’t help us with server communication, translations, routing, and so on.

2) JSX

We commonly write React code using JSX. But it can be written in plain JS too. As Example:

Creating an element:

const rootElement =
React.createElement(‘div’, {},
React.createElement(‘h1’, {style: {color: ‘red’}},
‘The world is yours’),
React.createElement(‘p’, {},
‘Say hello to my little friend’)
)

Rendering the created element:

ReactDOM.render(rootElement, document.getElementById(‘app’))

Using JSX -a “syntactic sugar for the React.createElement(component, props, …children) function”, we can refactor the createElement code to this:

const RootElement = (
<div>
<h1 style={{color: red}}>The world is yours</h1>
<p>Say hello to my little friend</p>
</div>
)

It will actually transpile to plain JS, Babel will do this during the build process.

3) Data goes down

In React data goes down the tree of the components. If you want to pass data from parent to child component you need to use props. From the JSX point of view, props are HTML attributes.

Parent component:

<div>
<Greetings color={red} text='Hello' />
</div>

In the child component, props are available under this.props.

Child component:

const Greetings = React.createClass({
render () {
const {color, text} = this.props
const divStyle = {padding: 10, backgroundColor: 'black'}
const headingStyle = {color: color}
return (
<div style={divStyle}>
<h1 style={headingStyle}>{text}</h1>
</div>
)
}
})

4) State

5) How Rendering Works

Every setState() call informs React about state changes. Then, React calls render() method to update the components representation in memory (Virtual DOM) and compares it with what’s rendered in the browser. If there are changes, React does the smallest possible update to the DOM.

Child components know that they need to re-render because their props changed.

Nothing to say more at this moment.