React ES6

ES6 Features Used in React

Modern React is written with ES6+ JavaScript. If you’re not comfortable with these features, mastering them will make React feel much more natural.

Arrow Functions

// Traditional function
function add(a, b) { return a + b; }

// Arrow function (implicit return when no braces)
const add = (a, b) => a + b;

// Arrow function in JSX โ€” common pattern
<button onClick={() => setCount(c => c + 1)}>+</button>

// Arrow function as component
const Greeting = ({ name }) => <h1>Hello, {name}!</h1>;

Destructuring

// Array destructuring โ€” useState returns an array
const [count, setCount] = useState(0);
const [first, , third]  = [1, 2, 3]; // skip second

// Object destructuring โ€” props
function Card({ title, body, author = "Anonymous" }) {
  return <div><h2>{title}</h2><p>{body}</p><small>{author}</small></div>;
}

// Rename on destructure
const { name: fullName, age: years } = user;

Spread Operator

// Arrays
const arr1 = [1, 2, 3];
const arr2 = [...arr1, 4, 5]; // [1, 2, 3, 4, 5]

// Objects (immutable state updates)
const user     = { name: "Alice", age: 30, role: "user" };
const promoted = { ...user, role: "admin" }; // Updates only role

// Spread props onto a DOM element
function Input({ className, ...rest }) {
  return <input className={"input " + className} {...rest} />;
}

Template Literals

const name = "Alice";

// ES5
const msg1 = "Hello, " + name + "! You have " + count + " messages.";

// ES6 template literal
const msg2 = `Hello, ${name}! You have ${count} messages.`;

// In JSX โ€” for class names
<div className={`card ${isActive ? "active" : ""} ${size}`}>

Optional Chaining & Nullish Coalescing

const user = null;

// Without optional chaining โ€” throws TypeError
const city = user.address.city;

// With optional chaining โ€” returns undefined safely
const city = user?.address?.city;

// Nullish coalescing: use fallback when value is null or undefined
const displayName = user?.name ?? "Guest";
const count       = data?.count ?? 0;

// In JSX
<p>{user?.profile?.bio ?? "No bio yet."}</p>

Modules (import / export)

// math.js
export const PI = 3.14159;
export function square(x) { return x * x; }
export default function add(a, b) { return a + b; }

// main.js
import add from "./math";           // default export
import { PI, square } from "./math"; // named exports
import * as math from "./math";     // all as namespace