What is React.js and Why I recommend it to other JavaScript Developers?
Sandip Das
Senior Cloud & DevOps Engineer | Kubernetes Expert | SRE, Platform Engineering, MLOps & AIOps Practioner | AWS Container Hero | Teacher | Mentor
React.js
This is a great choice to start with because it will expose you to concepts that will likely be prevalent in the web moving forward. Although the source code is just as unreadable as Angular's, the core API is amazingly simple - just a handful of lifecycle methods.
The trade off is that React is, famously, only the V (view) in MVC. If you're looking to work with remote data, you're going to have to quickly look into additional frameworks like Flux to support your app. Navigating all of these additional technologies can be challenging for a beginner, especially since many of them are rapidly coming into and falling out of style.
React.js is a JavaScript library for building user interfaces, built by top engineers at Facebook. This 8-week program will revolutionize the way you develop user interfaces for your own applications, or for your clients. Read on to learn more about this exciting new workshop, and why you should learn React.js as the next skill on your developer resume.
Facebook’s dev team built React to solve one problem: building large applications with data that changes over time. React lets you express how your app should look at any given point, and can automatically manage all UI updates when your underlying data changes. React.js is declarative, which means that React conceptually hits the “refresh” button any time data changes, and knows to only update the changed parts. React was used in-house at Facebook before being released as an open-source project to the public, so you can be certain it knows how to handle an astronomical amount of data.
React is a JavaScript library, but is often mistakenly referred to as a framework. Like many popular frameworks (Bootstrap, for example), React is all about reusable components. However, unlike frameworks, which are built with the goal of getting whole apps up and running quickly, the only thing you do with React is build components. As React.js’s core functionality, components make reusing code, testing, and separating concerns easy.
React was created by Facebook in 2013, and then released as an open-source project. This means that Facebook’s developers solved React’s major problems first, and then made the code available to the world. React.js is, for most developers, clean and easy to use right from the start.
React.js is the 5th most starred JavaScript library on Github, falling just behind Angular, D3, jQuery, and HTML5. It’s popularity is strong with plenty of room to grow. What does that mean to a junior developer? Learn React for lots of job opportunities!
One reason developers love React.js is because the library makes it easy to get started. You can drop in a single widget, or code your entire app. You can use React.js seamlessly with Node.js or AngularJS. This is a marked difference to using the Angular framework, which provides a much more rigid structure for your project (you can use ngReact to integrate react.js with existing angular.js project).
It may be a coincidence that React.js was made by the world’s largest social network, but this library plays exceptionally well with Node , Rails, AngularJS… anything. There’s even a Ruby gem for React! The only caveat is that you shouldn’t try mixing React with jQuery. React.js is meant to replace jQuery, so there’s no need to use both. Developers can squeeze in jQuery if they try, but the original dev team advises against using both.
The ability to mix and match means you don’t have to train your brain to “think in React.js” all the time. Angular, for example, requires developers to think in sync with the Angular framework. For experienced Angular developers, this will become second nature. Think of one as learning a new language, and as picking up a few words.
React.js makes building UI simpler than ever. You can pin chat messages or load photos in a view with the same piece of code. Universal rendering also means your apps will be fast beyond what you’re used to. React.js gives you server side goodies, like better SEO, and even lets you use the same code on the server and client side. Your apps will be faster and more responsive with less work from you.React.js is a true full stacker, and works with Android, desktop, iOS, or mobile. In a nutshell, React.js was made by developers, for developers, solving many of the compatibility issues and redundancies they discovered when trying to make their own user interfaces responsive to data.
The React.js dev team believes that happy developers mean happy users. Redux devtools let you preview changes without refreshing, and you can bounce between versions to check your work. Below I am going to discuss more of React.js programming guidelines , architecture and more.
Concepts of React.js
React has quite a small API. This makes it fun to use, easy to learn, and simple to understand. However, being simple does not mean it's familiar. There are a few concepts to cover before getting started. Let's look at each in turn.
React elements are JavaScript objects which represent HTML elements. They do not exist in the browser. They represent browser elements .
Components are developer created React elements. They're usually larger parts of the user interface which contain both the structure and functionality .
JSX
It’s called JSX, and it is a Javascript XML syntax transform. This lets you write HTML-ish tags in your Javascript. I say HTML-ish because there are a couple gotchas. You are really just writing XML based object representations.
For regular html tags, the attribute is and the attribute is in JSX because these are reserved words in Javascript. More differences can be reviewed here.
It's is a technique for creating React elements and components. For example is a React element written in JSX. The same React element can be written as JavaScript with . JSX is less effort to read and write and is transformed into JavaScript before running in the browser.
Useful links about JSX:
The Virtual DOM
The Virtual DOM is a JavaScript tree of React elements and components. React renders the virtual DOM to the browser to make the user interface visible. React observes the virtual DOM for changes and automatically mutates browser DOM to match the virtual DOM.
How does the Virtual DOM work?
Imagine you had an object that you modeled around a person. It had every relevant property a person could possibly have, and mirrored the persons current state. This is basically what React does with the DOM.
Now think about if you took that object and made some changes. Added a mustache, some sweet biceps and Steve Buscemi eyes. In React-land, when we apply these changes, two things take place. First, React runs a “diffing” algorithm, which identifies what has changed. The second step is reconciliation, where it updates the DOM with the results of diff.
The way React works, rather than taking the real person and rebuilding them from the ground up, it would only change the face and the arms. This means that if you had text in an input and a render took place, as long as the input’s parent node wasn’t scheduled for reconciliation, the text would stay undisturbed.
Because React is using a fake DOM and not a real one, it also opens up a fun new possibility. We can render that fake DOM on the server, and boom, server side React views.
Useful links, other virtual DOM libraries
- React’s diff algorithm
- The Secrets of React's virtual DOM
- Why is React's concept of virtual DOM said to be more performant than dirty model checking?
- virtual-dom
With a small understanding of these concepts we can move on to using React. We'll build a series of user interfaces, each adding a layer of functionality on the previous. We'll build a photo stream similar to instagram - example applications don't get much better than this!
Rendering
The first order of business is rendering a virtual element (a React element or component). Remember, since a virtual element exists only in JavaScript memory, we must explicitly tell React to render it to the browser DOM
React.render(<imgsrc='https://tinyurl.com/lkevsb9'/>,document.body);
The render function accepts two arguments; a virtual element and a real DOM node.
React takes the virtual element and inserts it into the given DOM node.
The image is now visible in the browser.
Components
Components are the heart and soul of React. They are custom React elements. They are usually extended with unique functionality and structure.
When using the method above, our first argument is the component we want to render, and the second is the DOM node it should mount to. We can use the method to create custom component classes. It takes an object of specifications as it’s argument. Lets create one below:
varPhoto=React.createClass({render:function(){return<imgsrc='https://tinyurl.com/lkevsb9'/>}});React.render(<Photo/>,document.body);
Props
Props can be thought of as a component's options. They're given as arguments to a component and look exactly like HTML attributes.
When we use our defined components, we can add attributes called props. These attributes are available in our component as and can be used in our render method to render dynamic data:
var Photo = React.createClass({
render: function() {
return (
<div className='photo'>
<img src={this.props.src} />
<span>{this.props.caption}</span>
</div>
);
}
});
Inside the React render function, two props are passed to the Photo component; src and caption.
Inside the component's render function the src prop is used as the src for the React image element. The caption prop is also used as plain text within the React span element.
It's worth noting that a component should never change its props, they're immutable. If a component has data that's mutable, use the state object.
Specs, Lifecycle & State
The method is the only required spec for creating a component, but there are several lifecycle methods & specs we can use that are mighty helpful when you actually want your component to do anything.
Lifecycle Methods
- componentWillMount – Invoked once, on both client & server before rendering occurs.
- componentDidMount – Invoked once, only on the client, after rendering occurs.
- shouldComponentUpdate – Return value determines whether component should update.
- componentWillUnmount – Invoked prior to unmounting component.
Specs
- getInitialState – Return value is the initial value for state.
- getDefaultProps – Sets fallback props values if props aren’t supplied.
- mixins – An array of objects, used to extend the current component’s functionality.
There are several more specs & lifecycle methods that you can read about here.
State
The state object is internal to a component. It holds data which can change over time.
Every component has a object and a object. State is set using the method. Calling triggers UI updates and is the bread and butter of React’s interactivity. If we want to set an initial state before any interaction occurs we can use the method. Below, see how we can set our component’s state:
var Photo = React.createClass({
toggleLiked: function() {
this.setState({
liked: !this.state.liked
});
},
getInitialState: function() {
return {
liked: false
};
},
render: function() {
var buttonClass = this.state.liked ? 'active' : '';
return (
<div className='photo'>
<img src={this.props.src} />
<div className='bar'>
<button onClick={this.toggleLiked} className={buttonClass}>
?
</button>
<span>{this.props.caption}</span>
</div>
</div>
);
}
});
React.render(<Photo src='https://tinyurl.com/lkevsb9' caption='Hong Kong!'/>, document.body);
Having state in a component introduces a bit more complexity.
The component has a new function . React calls this function when the component is initialised. The returned object is set as the component's initial state (as the function name implies).
The component has another new function . This function calls on the component which toggles the value.
Within the component's render function a variable is assigned either 'active' or nothing - depending on the state.
is used as a class name on the React button element. The button also has an event handler set to the function.
Here's what happens when the component is rendered to the browser DOM:
- When the component's button is clicked, is called
- The state is changed
- React re-renders the component to the virtual DOM
- The new virtual DOM is compared with the previous virtual DOM
- React isolates what has changed and updates the browser DOM
In this case, React will change the class name on the button.
Events
React also has a built in cross browser events system. The events are attached as properties of components and can trigger methods. Lets make our count increment below using events:
/** @jsx React.DOM */
var Counter = React.createClass({
incrementCount: function(){
this.setState({
count: this.state.count + 1
});
},
getInitialState: function(){
return {
count: 0
}
},
render: function(){
return (
<div class="my-component">
<h1>Count: {this.state.count}</h1>
<button type="button" onClick={this.incrementCount}>Increment</button>
</div>
);
}
});
React.render(<Counter/>, document.getElementById('mount-point'));
Composition
Composition means combining smaller components to form a larger whole. For example the component could be used inside a component, like so:
var Photo = React.createClass({
toggleLiked: function() {
this.setState({
liked: !this.state.liked
});
},
getInitialState: function() {
return {
liked: false
};
},
render: function() {
var buttonClass = this.state.liked ? 'active' : '';
return (
<div className='photo'>
<img src={this.props.src} />
<div className='bar'>
<button onClick={this.toggleLiked} className={buttonClass}>
?
</button>
<span>{this.props.caption}</span>
</div>
</div>
);
}
});
var PhotoGallery = React.createClass({
render: function() {
var photos = this.props.photos.map(function(photo) {
return <Photo src={photo.url} caption={photo.caption} />
});
return (
<div className='photo-gallery'>
{photos}
</div>
);
}
});
var data = [
{
url: 'https://tinyurl.com/lkevsb9',
caption: 'Hong Kong!'
},
{
url: 'https://tinyurl.com/mxkwh56',
caption: 'Cows'
},
{
url: 'https://tinyurl.com/nc7jv28',
caption: 'Scooters'
}
];
React.render(<PhotoGallery photos={data} />, document.body);
The component is exactly the same as before.
There's a new component which generates 3 components from some fake data passed in as a .
React.js Cheat Sheet (for them who are too busy like me :) )
https://ricostacruz.com/cheatsheets/react.html
This should be enough to get started building user interfaces with React. The React docs cover everything in detail and must take some time to check out the React API and read up a bit on JSX. I highly recommend reading it. Also if you are planning to build a mobile app ,you may consider react native.
React is fast and scalable, I have went through how React handles the rendering and what the component-driven development is. These are the very basics. I will be writing next about flux and how to integrate react.js with node.js (express.js , MEAN.IO, Sails.js and Meteor.js) .
Thanks for reading!
Love the post? Hate the post? Have other Tips? Please Leave a comment below!
About the Author
Sandip Das is a tech start-up adviser as well as working for multiple international IT firms , tech-entrepreneurs as Individual IT consultant / Sr. Web Application developer / JavaScript Architect , worked as a team member, helped in development and in making IT decision . His desire is to help both the tech-entrepreneurs & team to help build awesome web based products , make team more knowledgeable , add new Ideas to give WOW expression in product.
Information technology
7 年Thank you so much for your article, can you provide us with the source code for the "Instagram" codes?
Senior Software Engineer | JavaScript | React | NextJs | NestJs
7 年This is my another dream *)
Senior Software Engineer at Selfbook
8 年"Because React is using a fake DOM and not a real one, it also opens up a fun new possibility. We can render that fake DOM on the server, and boom, server side React views." Great article....
Senior Manager, Technical Recruiting at Telnyx
8 年Great article