DEV Community

Kevin Ball
Kevin Ball

Posted on • Originally published at zendev.com on

Learning React: Is This ES6 or React?

In a recent blog post about his struggle to learn React, Brad Frost highlighted an issue that I've heard from developer after developer:

Because React and ES6 are very much intertwined, I have a hard time digesting any given block of code. What’s coming from React? What’s just ES6 JavaScript?

Knowing what is what can help tremendously in figuring out what to search for and where to learn it. Below I break down a lot of the syntax you'll see in React tutorials and examples.

For each feature, I show a couple examples of what it might look like, identify where it is coming from, give you a quick overview of what is called and what it does, and link off to some resources that can help you learn about it.

Arrow Functions (ES6)

// example 1
this.handleChange = () => {
  this.doSomething();
  return;
}

// example 2
this.array.map(item => item.name);
Enter fullscreen mode Exit fullscreen mode

Arrow functions are one of the most popular new features in ES6. They combine a slick new syntax with an implicit bind that makes this inside the error function equal to this in the context that defined them.

The new syntax essentially consists of the list of arguments in parentheses, followed by a "fat arrow" (=>), followed by the function body.

For compactness, the parentheses can be neglected if there is only one argument. Additionally, if the function body is a single statement that returns a value, you can neglect both the the {} brackets around it and the return statement, leading to the compact syntax in the second example above. This example starts with an array of objects and returns an array of the name value of each object.

For those coming from other dynamic languages like Python or Ruby, arrow function semantics are very similar to lambda functions.

Promises (ES6)

api.get(someUrl).then((value) => {
    console.log(value);
}).catch((error) => {
    console.log(error);
});
Enter fullscreen mode Exit fullscreen mode

Promises are an alternative mechanism for dealing with asynchronisity than passing callback functions. Any time you see then in your code you can be pretty certain you're dealing with a promise.

A promise is essentially a placeholder for a value. The value may be there right away, or it may need to wait until some asynchronous action like an AJAX call before it can be resolved. Regardless, if you call then on a promise and pass a function, that function will be called when the value is available.

This pattern leads to a more natural pattern of dealing with asynchronous programming than chained callbacks, because you can pass these objects around, return them, chain them, and all sorts of fun stuff.

Here's a good introduction to their use: A Simple Guide to ES6 Promises.

Let and Const (ES6)

const temperature = this.props.temperature;
let iterator = 1;
Enter fullscreen mode Exit fullscreen mode

When JavaScript was first standardized, there was only one keyword for declaring a variable: var. The semantics for var were a little weird too - scoping was strange, and you could shadow variables in ways that were hard for people to understand.

ES6 took this problem on, defining two new keywords for declaring variables with simpler semantics. Both let and const have block scope, something that is closer to what most developers expect naturally. The const keyword implies the reference cannot change (though if the reference is to an object or array, the internals can change - this is not immutability), while let allows the reference to change.

Most developers have taken to using exclusively let and const, with var being a strong code smell of legacy code.

You can learn more about the differences in this excellent post by Wes Bos: Let vs Const.

Object Destructuring (ES6)

// example 1
const { props, state } = this;

// example 2
const [first, second] = array;
Enter fullscreen mode Exit fullscreen mode

Object destructuring is a mechanism for directly assigning properties from an object or array into variables in a way that looks like object literal syntax.

By far the most common use from what I've seen is to pick off particular properties of an object for use inside of a function, as in the first example above.

Destructuring also supports default values, and can be used inside of function arguments, leading to powerful patterns like this: Elegant patterns in modern JavaScript: RORO.

Classes (ES6)

class MyClass extends BaseClass {
  constructor() {
    super();
    this.doSomething();
  }
}
Enter fullscreen mode Exit fullscreen mode

The class and extends keywords and the special function constructor are parts of ES6 classes. These classes are a new syntax for developing JavaScript in an object oriented manner that feels more similar to other object oriented languages.

This new syntax is not a new approach to object orientation - underneath it, JavaScript still uses a prototypal inheritance model - but they do make it easier to reason about what is going on.

Here are a couple good articles with different takes on JavaScript Classes: Javascript : Prototype vs Class and Let’s demystify JavaScript’s ‘new’ keyword.

Props and State (React)

constructor(props) {
  super(props);
  this.state = {date: new Date()};
}
Enter fullscreen mode Exit fullscreen mode

The concepts of props and state were formalized by React and are becoming accepted throughout component oriented frameworks.

First, props refers to data that is passed into a component and influences how that component behaves. The component cannot change props directly - it does not own this data - but it reacts to changes in props, so if the props change, the component rerenders.

Next, state refers to data that the component itself controls. This state may directly influence how the component lays out, or may just be used for internal bookkeeping - it's up to the component. The component owns this data and can change it, but also reacts automatically to changes in state, rerendering when it changes. Changes need to happen through a specified method, setState, which is covered below.

Here is an excellent introduction to props and state: ReactJS: Props vs. State.

setState (React)

this.setState({isLoggedIn: true});
Enter fullscreen mode Exit fullscreen mode

Except in the constructor of a component, changes to the state of a React component need to happen via the setState method. This allows React to batch these changes, and automatically trigger re-rendering of the component on changes.

Spread/Rest (ES6)

// example 1
const image = { ...image, ...attributes };

// example 2
this.setState({ ...this.state.image, ...attributes });
Enter fullscreen mode Exit fullscreen mode

The Spread operator, aka the ... operator, essentially takes an array or an object and expands it into its set of items. This lets you do fun things like merging of objects or creating shallow copies of objects with a very tight syntax.

I wrote a breakdown of the spread operator here: Understanding the Spread Operator in JavaScript.

Template Literals (ES6)

const str = `What's going on, ${name}?`;
Enter fullscreen mode Exit fullscreen mode

Template literals are a new way of creating strings in JavaScript. Essentially, they allow you to plug javascript straight into strings without needing to do lots of concatenation and adding of strings the way you used to.

A template literal is a string within backticks

``, and then anything inside of a${}` gets evaluated as JavaScript.

The most common use is simply to put variables in, but any single JavaScript expression can be inside of the ${}, including functions - the return value will be injected into the string.

Here's a good introduction to template literals, and their related feature tagged templates, on CSS Tricks: Template Literals.

Lifecycle Hooks (React)



componentWillMount() {
}

componentDidMount() {
}

componentWillReceiveProps() {
}

componentWillUnmount() {
}


Enter fullscreen mode Exit fullscreen mode

Functions that look like this - in React named in a consistent way starting with component then Will or Did, and some description, are known as Lifecycle hooks.

These functions allow you to execute logic at certain times in the component lifecycle. React does a lot for you automatically, but sometimes you need to nudge it to do more at particular points in the process.

Some of the most common uses are things like loading data when a component is mounted, or taking a copy of props for some local state.

Here is an introduction to some of the most common lifecycle hooks: 30 Days of React: Lifecycle Hooks.

JSX (React)



// example 1
const element = <h1>Hello, world!</h1>;

// example 2
const element = (
  <h1>
    Hello, {formatName(user)}!
  </h1>
);


Enter fullscreen mode Exit fullscreen mode

JSX is syntax extension to JavaScript that allows embedding HTML-like templates directly into your JavaScript.

It is one of the most controversial pieces of React, turning many long-time web developers off while being touted by advocates as dramatically increasing productivity. It is possible to use React without JSX, but JSX is the recommended approach.

Two quick points to understand about JSX. First, if you have a single line of markup (like the first example above), you can directly put the markup into your JavaScript, while if you are going multiple lines you need to surround it with parenthesis.

Second, anything within single brackets, {} gets evaluated as JavaScript. This allows the easy embedding of logic or dynamic values into your markup.

Here's an in-depth tutorial on JSX: JSX in Depth.

Wrapping Up

I'm confident there are more elements of both React and ES6 that are confusing. If you run into one that I didn't cover, don't hesitate to reach out to me in the comments below or on Twitter and I'll help you understand it and add it to the list.


P.S. —  If you’re interested in these types of topics, I send out a weekly newsletter called the ‘Friday Frontend’. Every Friday I send out 15 links to the best articles, tutorials, and announcements in CSS/SCSS, JavaScript, and assorted other awesome Front-end News. Sign up here: https://zendev.com/friday-frontend.html

Top comments (0)