Beginner50 min read

ES6+ JavaScript Features for React

Learn modern JavaScript features essential for React: arrow functions, template literals, modules, and more. These features are used throughout React code.

Topics Covered:

ES6 FeaturesArrow FunctionsTemplate LiteralsModulesClassesDefault Parameters

Prerequisites:

  • JavaScript Functions and Scope

Video Tutorial

Overview

ES6 (ECMAScript 2015) and later versions introduced many features that are now standard in React development. Understanding these modern JavaScript features is essential for reading and writing React code. This tutorial covers arrow functions, template literals, modules, classes, default parameters, and other ES6+ features that you'll see constantly in React applications.

Arrow Functions (ES6)

Arrow functions provide a concise syntax for writing functions. They're the standard in React code. Arrow Function Syntax: • Shorter than regular functions • Implicit return for single expressions • Lexical this binding • No arguments object When to Use: • Event handlers in React • Array methods (map, filter) • Callback functions • React components Differences from Regular Functions: • No own this binding • No arguments object • Cannot be used as constructors

Code Example:
// Regular function
function add(a, b) {
  return a + b;
}

// Arrow function
const add = (a, b) => a + b;

// Arrow function with body
const add = (a, b) => {
  return a + b;
};

// Single parameter (no parentheses needed)
const square = x => x * x;

// No parameters
const greet = () => console.log("Hello!");

// Arrow functions in array methods
const numbers = [1, 2, 3, 4, 5];
const doubled = numbers.map(num => num * 2);
const evens = numbers.filter(num => num % 2 === 0);
const sum = numbers.reduce((total, num) => total + num, 0);

// Arrow functions in React (preview)
const Button = ({ label, onClick }) => (
  <button onClick={onClick}>
    {label}
  </button>
);

// Event handlers
const handleClick = () => {
  console.log("Clicked!");
};

// In component
<button onClick={() => handleClick()}>Click</button>

Arrow functions are the standard in React. They provide concise syntax and lexical this binding. Used extensively for event handlers, array methods, and React components.

Template Literals (ES6)

Template literals provide an easy way to create strings with embedded expressions. Template Literal Syntax: • Use backticks (`) instead of quotes • Embed expressions with ${} • Support multi-line strings • More readable than concatenation Use Cases: • String interpolation • Multi-line strings • Dynamic content • React JSX (similar concept)

Code Example:
// Old way (string concatenation)
const name = "Alice";
const greeting = "Hello, " + name + "!";

// Template literal (ES6)
const greeting = `Hello, ${name}!`;

// Multi-line strings
const message = `This is a
multi-line
string`;

// Expressions in template literals
const a = 5;
const b = 10;
const result = `${a} + ${b} = ${a + b}`;
// "5 + 10 = 15"

// Function calls
const getName = () => "Alice";
const greeting = `Hello, ${getName()}!`;

// Template literals in React (preview)
function Greeting({ name, age }) {
  return (
    <div>
      <h1>Hello, {name}!</h1>
      <p>You are {age} years old</p>
    </div>
  );
}

// Similar concept in JSX
const className = `btn btn-${variant} btn-${size}`;

Template literals make string creation easier and more readable. They support expressions and multi-line strings. Similar concept to JSX interpolation in React.

Destructuring (ES6)

Destructuring allows you to extract values from arrays and objects. It's used extensively in React. Array Destructuring: • Extract by position • Skip values • Rest operator Object Destructuring: • Extract by property name • Rename variables • Default values • Nested destructuring In React: • Destructure props • Destructure state • Function parameters

Code Example:
// Array destructuring
const [first, second] = [1, 2];

// Object destructuring
const { name, age } = { name: "Alice", age: 30 };

// Destructuring in React (preview)
function UserCard({ name, age, email }) {
  // Instead of props.name, props.age, etc.
  return (
    <div>
      <h2>{name}</h2>
      <p>{age} years old</p>
    </div>
  );
}

// Destructuring with defaults
function Button({ label, onClick, variant = "primary" }) {
  return <button className={`btn-${variant}`} onClick={onClick}>{label}</button>;
}

// Destructuring state
const [user, setUser] = useState({ name: "Alice", age: 30 });
const { name, age } = user;

Destructuring is used constantly in React for props, state, and function parameters. Makes code cleaner and more readable.

Spread Operator (ES6)

The spread operator expands arrays and objects. Essential for React state management. Spread Uses: • Copy arrays/objects • Combine arrays/objects • Pass arguments • Update state immutably In React: • State updates • Props spreading • Combining arrays

Code Example:
// Spread arrays
const arr1 = [1, 2, 3];
const arr2 = [...arr1, 4, 5];

// Spread objects
const user = { name: "Alice", age: 30 };
const updated = { ...user, age: 31 };

// Spread in React (preview)
function Component() {
  const [user, setUser] = useState({ name: "Alice", age: 30 });
  
  const updateAge = () => {
    setUser({ ...user, age: user.age + 1 });
  };
  
  return <button onClick={updateAge}>Age: {user.age}</button>;
}

// Adding to array
const [todos, setTodos] = useState([]);
const addTodo = (newTodo) => {
  setTodos([...todos, newTodo]);
};

Spread operator is essential for React state updates. Always create new objects/arrays instead of mutating. Used for immutable state updates.

Modules: import and export (ES6)

ES6 modules allow you to organize code into separate files. React uses this extensively. Export: • export - Named export • export default - Default export • Can export functions, objects, classes Import: • import { name } - Named import • import name from - Default import • import * as - Namespace import In React: • Component files • Utility files • Hook files • Type files

Code Example:
// Exporting (utils.js)
export function formatDate(date) {
  return date.toLocaleDateString();
}

export const API_URL = "https://api.example.com";

export default function helper() {
  // Default export
}

// Importing
import { formatDate, API_URL } from "./utils";
import helper from "./utils"; // Default import
import * as utils from "./utils"; // All exports

// React example (preview)
// Button.jsx
export function Button({ label, onClick }) {
  return <button onClick={onClick}>{label}</button>;
}

// App.jsx
import { Button } from "./Button";

function App() {
  return <Button label="Click me" onClick={() => {}} />;
}

// Hooks
// useCounter.js
export function useCounter(initial = 0) {
  const [count, setCount] = useState(initial);
  return { count, setCount };
}

// Component.jsx
import { useCounter } from "./hooks/useCounter";

ES6 modules organize code into files. React uses this for components, hooks, and utilities. export and import are standard in React projects.

Conclusion

ES6+ features are the foundation of modern React code. You've learned arrow functions, template literals, destructuring, spread operator, and modules. These features are used constantly in React - in components, hooks, event handlers, and state management. Practice these features until they become natural. With this JavaScript foundation, you're now ready to dive into React development!