React ES6 Variables

🔰 React ES6 Variables

ES6 introduced two new ways of declaring variables:

Keyword Reassignable? Scope Common Use in React
var ✔ Yes Function scope ❌ Avoid
let ✔ Yes Block scope {} ✔ Use for changable values
const ❌ No Block scope {} ⭐ Best for constants, functions, components

In React, we rarely use var — most code uses:

👉 const (default)
👉 let (only if value will change)


🚀 Example Comparison

❌ Using var:

Problems with var:

  • Can be re-declared accidentally.

  • Not block-scoped (causes bugs).


✅ Using let:

Use let when variable value will change — useful in loops or temporary values.


⭐ Using const (Recommended)


 

const does not mean immutable object — only reassignment is blocked.

Example:


🧠 Usage in React

📌 Declaring Components

React components are usually declared with const:


📌 Using Variables in JSX


 


📌 Using let in Logic


 


📌 Variables with State (Hook Example)


 

  • count and setCount are declared with const because React controls their value changes.


🎯 When to Use What?

Scenario Use
Value never reassigned const
Loop or temporary variable changes let
Old JavaScript / not recommended var

🏷 Summary

React ES6 variables help write clean and error-free code:

const — best for components, functions, props, state
let — use only for changing values
var — avoid in modern React

You may also like...