Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Fun With React: A Quick Overview

DZone's Guide to

Fun With React: A Quick Overview

React has become arguably the most popular JavaScript framework currently in use. What are the key elements of React that help make it so popular? Let's dive in.

· Web Dev Zone ·
Free Resource

Deploy code to production now. Release to users when ready. Learn how to separate code deployment from user-facing feature releases with LaunchDarkly.

React in the Real World

Created by Facebook, React was initially released in 2013. React continued to gain momentum until it looked like it was going to hit a snag in 2017 over licensing. The BSD+Patents license that Facebook was insisting on created potential Intellectual Property issues for developers. Fortunately, in September of 2017 Facebook backed down and re-licensed React under the more acceptable MIT license. The current release is 16.2.

Like the other popular frameworks, React is a free, unlicensed library so there are no perfect usage statistics, but there are several places we can look to for a good idea of overall adoption. It has over 88K stars on GitHub, and over 7 million npm downloads per month. Some of this traffic might, of course, be from development machines or mirrors, but these are good quick stats to get an idea of just how popular the library is.

React Statistics

  • Over 88K stars on GitHub
  • Over 7M npm downloads per month

React broke one million downloads per month in Jan of 2016 and has been climbing steadily since then, topping 7 million by the end of 2017. While it dipped in Dec 2017, in Jan of 2018 it was back up over 7.5 Million.

 Download statistics for package "react" 2016-2017 - data by npm-stat.com

Core Concepts

React has some unique core concepts. It has a virtual DOM, JSX components, input properties, and props. Also, each React component has a state and a lifecycle, which we will go into.

React Core Concepts

  • Virtual DOM
  • JSX
  • Components
  • Props
  • State
  • Lifecycle

The Virtual DOM

The virtual DOM is a node tree, just like the DOM. If you're familiar with how the DOM works within a web browser then it will be easy to understand the virtual DOM. It's very similar, but it's all virtual. There's a list of elements, and attributes, and content that exists as JavaScript objects with properties. When we call a render function - and each React component has a render function - it actually creates a node tree from that React component whether it's just one single component, or whether we're rendering child components as well. It lists out the whole tree. It also updates that same tree whenever data models are changed - whenever we update state or change anything within the component.

React updates the real DOM in three steps. Whenever something has changed, the virtual DOM will re-render. Then the difference between the old virtual DOM and new virtual DOM will be calculated. Then from there, the real DOM will be updated based on these changes. Instead of constantly having to work with the real DOM, which is very expensive, everything is handled virtually until we absolutely need to update the DOM. At that point, we'll go ahead and do that expensive call.

JSX

JSX is officially an XML-like syntax that is close to HTML, but not quite HTML. It is actually JavaScript with HTML sprinkled in. It's really just syntactical sugar for something like this:

react.createElement(component, props, ...children)

Instead of working with the format in the example above, we'll use a much simpler format shown in the example below using the tag MyButton.

<MyButton color="blue" shadowSize={2}>
Click Me
</MyButton>

Becomes

React.createElement(
MyButton,
{ color: 'blue', shadowSize: 2 },
'Click Me'
)

It all stems from the react.createElement. Instead of having to create an element by hand, we have the component MyButton which has several different attributes that we pass into it. We don't have to deal with creating the element, and then defining the tag, and then passing in all the attributes and everything like that.

Components

React lets us split the UI into independent reusable pieces. Components are like JavaScript functions. We have an arbitrary amount of input, set the props, and then we return the React elements. We're always returning a render function that has the elements that we want it to display. It's very simple to begin with, but we can quickly get advanced with this. The render function is really key here because every component will have a render function. We'll see here we have the function Welcome(props), for example.

function Welcome(props) {
  return <h1>Hello, {props.name}</h1>;
}

We can also write it as @class Welcome which extends React.Component in the ES6 way if we want to work a little bit more with classes.

class Welcome extends React.Component {
  render() {
    return <h1>Hello, {this.props.name}</h1>;
  }
}

In the first example, we return the simple HTML element. In the ES6 example, we have the same thing but then render, and this is just a little bit more syntax thrown in for passing back an HTML element.

Props

Props is what gives our components and attributes overall properties. This is how we pass in data. This is how we deal with various different attributes. As we see here, in this example, we have the shopping list name, we pass in a name here, and we'll be able to use this.props.name while rendering this particular component. This is an easy way to pass data in and out.

class ShoppingList extends React.Component {
  render() {
    return (
      <div className="shopping-list">
        <h1>Shopping List for {this.props.name}</h1>
        <ul>
          <li>Bananas</li>
          <li>Cereal</li>
          <li>Cabbage</li>
        </ul>
      </div>
    );
  }
}

Each component has a state, and it actually manages its own state as well. This can be extracted and set in our code. As developers, we're actually responsible for updating and dealing with state. In the example below, we see here that in the beginning when we create this clock component in the constructor, we have this.state. We pass in a new date, and then we can actually output that in the render function. We can use states easily to perform common tasks like setting the state and extracting the state easily.

class Clock extends React.Component {
  constructor(props) {
    super(props);
    this.state = {date: new Date()};
  }

  render() {
    return (
      <div>
        <h1>Hello, world!</h1>
        <h2>It is {this.state.date.toLocaleTimeString()}.</h2>
      </div>
    );
  }
}

Each component has a specific lifecycle that we have control over. We have mounting, updating, and unmounting functions. We have a full list of different lifecycle hooks that we can subscribe too. The constructor, for example, can help us set up the initial state. Then, from there, we have other events that we can hook into.

Mounting

  • constructor()

  • componentWillMount()

  • render()

Updating

  • componentDidMount()

  • componentWillReceiveProps()

  • shouldComponentUpdate()

  • componentWillUpdate()

  • render()

Unmounting

  • componentDidUpdate()

  • componentWillUnmount()

Getting Started

The easiest way to get started with React is through create-react-app CLI. That's the official React CLI. Then we can create a new app, and that bootstraps the entire application. We simply use create-react-app my-app. Then we go ahead and kick things off with npm start. This command just runs through a custom npm script to kick off the app and set up a server for us, so we can start working on the app itself.

# Install create-react-app – React’s CLI
$ npm install –g create-react-app
# Create our app
$ create-react-app my-app
# Start our app
$ cd my-app
$ npm start

What's Next?

We covered a lot of content quickly to present a 'taste' of React and we have not done more than scratch the surface. However, this should be enough to give everybody a high-level look at what we have available within React.

Now that we have had a quick look at React, is React the right choice for you? There are other frameworks that are very popular - Angular and Vue in particular. While Vue and React share some similarities, Angular is very different. Whether or not it is the right choice for you depends on a number of factors. 

Deploy code to production now. Release to users when ready. Learn how to separate code deployment from user-facing feature releases with LaunchDarkly.

Topics:
react ,react.js ,web dev ,jsx ,virtual dom

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}