Es6 in ReactJS
ES6 (ECMAScript 2015) is a version of JavaScript that introduced many powerful features that are widely used in ReactJS. Understanding these features is essential when working with React.
✅ Key ES6 Features in ReactJS
📌 1. let and const
letandconstare used for variable declarations instead ofvar.const→ Use for constants (values that don't change).let→ Use for variables whose values may change.
Example:
const fetchData = async () => { try { const response = await fetch('https://jsonplaceholder.typicode.com/posts'); const data = await response.json(); console.log(data); } catch (error) { console.error("Error fetching data:", error); }};fetchData();
📌 8. Classes
ES6 introduces class-based components in React.
Example:
class Welcome extends React.Component { render() { return <h1>Hello, {this.props.name}const greet = (name = "Guest") => `Hello, ${name}!`;console.log(greet()); // Output: Hello, Guest!
📌 10. Object Literals
Shorthand for objects using variables.
Example:
const name = "React";const version = "18";const app = { name, version };console.log(app); // {name: "React", version: "18"}
✅ Final Thoughts
Use let and const instead of
var.Prefer arrow functions for cleaner callbacks and class methods.
Apply destructuring to simplify code.
Utilize spread/rest operators for managing objects and arrays.
Leverage async/await for handling API calls.