React ES6 Essentials
Modern React development relies heavily on ES6 (ECMAScript 2015) features to write cleaner, more efficient, and readable code. Understanding these features is essential for beginners and intermediate React developers.
1. let and const
let: Block-scoped variable, can be reassigned.const: Block-scoped constant, cannot be reassigned.
Example:
const name = "John";
let age = 25;
age = 26; // Allowed
Why important in React: Prevents accidental reassignment and improves code predictability.
2. Arrow Functions
- Simpler syntax for defining functions.
- Automatically binds
thisin class components.
Example:
const add = (a, b) => a + b;
const Greeting = () => <h1>Hello, React!</h1>;
3. Template Literals
Use backticks (``) to embed variables and expressions in strings.
Example:
Makes JSX dynamic and readable.
const name = "Jane";
const greeting = `Hello, ${name}! Welcome to React.`;
4. Destructuring
Extract values from objects or arrays into variables.
Example – Objects:
const user = { firstName: "John", lastName: "Doe" };
const { firstName, lastName } = user;
console.log(firstName); // John
Example – Arrays:
const fruits = ["Apple", "Banana"];
const [first, second] = fruits;
console.log(second); // Banana
Destructuring is commonly used in props and state:
function Greeting({ name }) {
return <h1>Hello, {name}!</h1>;
}
5. Default Parameters
Provide default values for function parameters.
Example:
Useful in React for optional props.
const greet = (name = "Guest") => `Hello, ${name}!`;
console.log(greet()); // Hello, Guest!
6. Spread & Rest Operators
- Spread (
...): Expand elements of arrays/objects. - Rest (
...): Collect remaining elements.
Example – Arrays:
const arr1 = [1, 2];
const arr2 = [...arr1, 3, 4]; // [1,2,3,4]
Example – Objects:
Commonly used for updating state in React.
const user = { name: "John", age: 25 };
const updatedUser = { ...user, age: 26 };
7. Modules – import & export
ES6 modules allow clean code separation.
Example – Export:
export const Greeting = () => <h1>Hello</h1>;
Example – Import:
Enables component reuse across files.
import { Greeting } from './Greeting';
8. Array Methods (map, filter, find)
Essential for rendering lists and manipulating data in React.
Example – map for rendering list:
filter and find are used for conditional rendering and searching data.
const fruits = ["Apple", "Banana"];
const fruitList = fruits.map((fruit) => <li key={fruit}>{fruit}</li>);
