ES6 Arrow Functions

React ES6 Arrow Functions

Arrow functions are one of the most popular features introduced in ES6. They allow you to write shorter, more concise function syntax. More importantly for React developers, they handle the this keyword much more predictably than traditional functions.


Standard Function vs Arrow Function

Let's look at how standard JavaScript functions differ from ES6 arrow functions.

Standard Function (Before ES6)

hello = function() {
  return "Hello World!";
}

Arrow Function

With arrow functions, you can remove the function keyword entirely and use the "fat arrow" => symbol instead.

hello = () => {
  return "Hello World!";
}

Implicit Returns

If your function contains only one statement, and that statement returns a value, you can remove the brackets {} and the return keyword. This is known as an implicit return.

// Arrow Function With Implicit Return
hello = () => "Hello World!";

Note: If your function has multiple lines of code, you must use curly braces and the return keyword.


Handling Parameters

If you have parameters, you place them inside the parentheses.

hello = (val) => "Hello " + val;

If there is only one parameter, you can optionally skip the parentheses entirely:

hello = val => "Hello " + val;

Why Arrow Functions are Crucial in React

In React, arrow functions are incredibly common. They are used in two major ways: defining functional components and handling events.

1. Defining Functional Components

It has become a standard convention in the React community to define functional components using arrow functions.

const MyComponent = () => {
  return <h1>I am an arrow function component!</h1>;
};

2. The this Keyword Issue

In traditional JavaScript functions, the this keyword represents the object that called the function. This behavior caused massive headaches in React class components, where event handlers would lose their connection to the component instance, causing this.setState to be undefined.

Arrow functions do not have their own this. Instead, they inherit this from the parent scope at the time they are defined (lexical scoping). This completely solved the binding issue in React.

Old Way (Binding Required):

class Header extends React.Component {
  constructor(props) {
    super(props);
    this.changeColor = this.changeColor.bind(this); // Tedious!
  }
  changeColor() {
    // Traditional function loses "this" context without binding
  }
}

Modern ES6 Way (Arrow Functions):

class Header extends React.Component {
  // Arrow function automatically binds "this" to the component instance
  changeColor = () => {
    this.setState({color: "blue"});
  }
}

Summary


Exercise

?

What is a key benefit of using Arrow Functions inside React class components?