const is a signal that the variable won’t be reassigned.

let is a signal that the variable may be reassigned

Additional things to ponder:

  • Use const by default
  • Use let only if rebinding is needed
  • const does not indicate that a value is ‘constant’ or immutable.

    const foo = {};
    foo.bar = 10;
    console.log(foo.bar); // --> 10
    

    Only the binding is immutable. ie using an assignment operator or a unary or postfix -- or ++ operator on a const variable throws a TypeError exception

  • ES6 const and let are hoisted too. Although the identifiers has the same memory reference from compile time, they cannot be accessed before declaration in the code. (but not as we thought the declaration would be physically moved to the top in the scope) ;)

Answer from yadhu on Stack Overflow
🌐
W3Schools
w3schools.com › react › react_es6_variables.asp
React ES6 Variables
React Compiler React Quiz React ... Bootcamp React Certificate ... Before ES6 there was only one way of defining your variables: with the var keyword. If you did not define them, they would be assigned to the global object. Unless you were in strict mode, then you would get an error if your variables were undefined. Now, with ES6, there are three ways of defining your variables: var, let, and const...
Discussions

How come, we can modify the const variable in react but not in vanilla js ?
React is Javacript, same rules apply If you attempt const [val, setVal] = useState(1); val = 3; you get an error, because val is const. - "But I can modify val by calling setVal!" No. By calling setVal you can modify the value stored inside the state (kept inside React, tied to your React component). But you are not changing ''val' (the local variable that lives inside the funcion). True, in the next render, the function body (which includes the line quoted above) will run anew, and then a completely new local const variable called `val` will be created and initialized with the new value stored in the state. More on reddit.com
🌐 r/reactjs
13
0
August 31, 2022
Why do we use "const" for useState instead of "let"?
The "remembering" happens outside of your function. When you call setState(), React maintain's it's own internal store where they keep track of values, and updates it there. It then it re-renders by calling App(), running your entire function again So when you are doing useState(), you are basically just asking react "Give me the current value of the [first] state variable used in the App component" and "Give me a function that lets me change it". So the value "count" here isn't the actual count that you can modify, but just the current value of what is in React's store when App() was ran. A tiny way to visualize it is as this: const getCount = () => 1; function App() { const count = getCount(); } More on reddit.com
🌐 r/reactjs
79
121
October 18, 2022
How to define constants in ReactJS - Stack Overflow
React is just a library for JavaScript. React does not subsume JavaScript. In particular, when you go down to something as unrelated from UI code as how to declare constants, you really shouldn’t be asking how React lets you do that, but rather how to go about doing that in JavaScript in general. More on stackoverflow.com
🌐 stackoverflow.com
reactjs - Simple let or const variables in react - Stack Overflow
I am new to react and I'm wondering if it is good practice to use simple let or const variables inside react functional components. I know there are hooks like useState, useRef and useMemo / useCal... More on stackoverflow.com
🌐 stackoverflow.com
🌐
NGCC in Angular Ivy
iq.js.org › questions › react › how-to-define-constants-in-react
How to define constants in React?
October 14, 2022 - In React, you can define constants using the const keyword. For example: ... This creates a constant named MY_CONSTANT with the value "hello". Constants are like variables, except that their value cannot be changed once they are assigned.
🌐
Educative
educative.io › the road to react: the one with class components › es6 const and let
ES6 const and let
However, when the variable is an array or object, the values it holds can get updated through indirect means: ... There are varying opinions about when to use const and when to use let. I would recommend using const whenever possible to show the intent of keeping your data structures immutable, so you only have to worry about the values contained in objects and arrays. Immutability is embraced in the React ecosystem, so const should be your default choice when you define a variable, though it’s not really about immutability, but about assigning variables only once.
🌐
GeeksforGeeks
geeksforgeeks.org › how-to-declare-constant-in-react-class
How to declare constant in react class ? | GeeksforGeeks
June 21, 2022 - Now move to the constantDemo folder using the following command: ... import React, { Component } from "react"; class App extends Component { static get myConstant() { return { name : "GFG", id : 1 } } render() { return ( <div>My constant is : {JSON.stringify(this.constructor.myConstant)}</div> ); } } export default App
🌐
React Native
reactnative.dev › docs › intro-react
React Fundamentals · React Native
February 20, 2026 - You can learn more about other kinds of Hooks in the React documentation. ... Then you declare the component’s state by calling useState inside its function. In this example, useState creates an isHungry state variable: ... You can use useState to track any kind of data: strings, numbers, Booleans, arrays, objects. For example, you can track the number of times a cat has been petted with const [timesPetted, setTimesPetted] = useState(0)!
Find elsewhere
🌐
Educative
educative.io › the road to react: the one with class components › es6 const and let
ES6 const and let - The Road to React: The One with Class ...
It shows the intent of not changing (re-assigning) the variable even though its content can be changed. import React, { Component } from 'react'; import './App.css'; class App extends Component { render() { const helloWorld = 'Welcome to the Road to learn React'; return ( <div className="App"> <h2>{helloWorld}</h2> </div> ); } } export default App;
🌐
Pluralsight
pluralsight.com › tech insights & how-to guides › tech guides & tutorials
How to Use Variables within Classes | Pluralsight
March 19, 2020 - In the above example, the state object will be static, and this means we can pass it to the child component and it will act as a constant value. State is one of the widely used terms in React.
🌐
TutorialsPoint
tutorialspoint.com › how-to-declare-constants-in-react-class
How to Declare Constants in React Class?
July 17, 2023 - Declaring constants in React class components provides a way to store values that remain unchanged throughout the component's lifecycle. Whether using static class properties or class?level variables, constants enhance code readability, and ...
🌐
Reddit
reddit.com › r/reactjs › why do we use "const" for usestate instead of "let"?
r/reactjs on Reddit: Why do we use "const" for useState instead of "let"?
October 18, 2022 -

Noob question maybe but I was just thinking about this. I found a stackoverflow answer to this question that was along the lines of "When the component is rerendered, the function is executed again, creating a new scope, creating a new state variable"

But components rerender only when the state changes, so that means it's changing the const variable first, and then rerendering the component which creates a new scope?

E.g

function App() {
    const [count, setCount] = useState(0)
    
    function handleChange() {
        setCount(count + 1)
    }
    ....
}

Unless setCount(count + 1) triggers a re-render before the count changes. So is the order:

  1. setCount is fired

  2. component rerenders with new scope

  3. react remembers old count variable

  4. count = old variable + 1

Is that how it works?

Top answer
1 of 8
49

You don't need to use anything but plain React and ES6 to achieve what you want. As per Jim's answer, just define the constant in the right place. I like the idea of keeping the constant local to the component if not needed externally. The below is an example of possible usage.

import React from "react";

const sizeToLetterMap = {
  small_square: 's',
  large_square: 'q',
  thumbnail: 't',
  small_240: 'm',
  small_320: 'n',
  medium_640: 'z',
  medium_800: 'c',
  large_1024: 'b',
  large_1600: 'h',
  large_2048: 'k',
  original: 'o'
};

class PhotoComponent extends React.Component {
  constructor(args) {
    super(args);
  }

  photoUrl(image, size_text) {
    return (<span>
      Image: {image}, Size Letter: {sizeToLetterMap[size_text]}
    </span>);
  }

  render() {
    return (
      <div className="photo-wrapper">
        The url is: {this.photoUrl(this.props.image, this.props.size_text)}
      </div>
    )
  }
}

export default PhotoComponent;

// Call this with <PhotoComponent image="abc.png" size_text="thumbnail" />
// Of course the component must first be imported where used, example:
// import PhotoComponent from "./photo_component.jsx";
2 of 8
32

If you want to keep the constants in the React component, use statics property, like the example below. Otherwise, use the answer given by @Jim

var MyComponent = React.createClass({
    statics: {
        sizeToLetterMap: {
            small_square: 's',
            large_square: 'q',
            thumbnail: 't',
            small_240: 'm',
            small_320: 'n',
            medium_640: 'z',
            medium_800: 'c',
            large_1024: 'b',
            large_1600: 'h',
            large_2048: 'k',
            original: 'o'
        },
        someOtherStatic: 100
    },

    photoUrl: function (image, size_text) {
        var size = MyComponent.sizeToLetterMap[size_text];
    }
🌐
Medium
ian-marshall.medium.com › defining-components-with-const-vs-class-in-react-bf43bb7cae74
Defining components with const vs class in React | by Ian Marshall | Medium
May 25, 2021 - As it happens, class components in React came after functional components, aka components defined with const.
Top answer
1 of 2
2

Using let or const is perfectly fine. Sometimes you need to declare variables that are derived from props or states, in order to make the code declarative and readable.

Regarding your performance doubt, you can always use useMemo hook to memoize the derived value and avoid calculating it on each render. But this should be avoided as long as your code is not expensive computationally.

export default function MyComponent(props) {

  const otherCondition = props.content.length > 20;

  const myVariable = useMemo(() => {
    let myVariable = 0;
    if (props.isDisabled && otherCondition) {
      // ...more complex checks...
      myVariable = 1;
    } else {
      myVariable = 2;  
    }
    return myVariable
  }, 
  [props.isDisabled, otherCondition])

  return (
    <>
     {/* some JSX */}
    </>
  );

}

2 of 2
0

Use of const is preferable if your variable is not getting assigned again, use linters in VS Code and it will let you know where a variable can be const.

Use of let if you wish to make a variable re-assignable. It is less used in practice though. Let us assume a case that you need to use a variable and again re-assign it in a function or a loop, then let should be used.

Regarding hooks then they are of great help, they make us code better and code complex. As you mentioned that hooks do re-renders if data changes, and if there is some changes in DOM element, then only it is assigned to the create.reactElement. Regarding re-renders, you can have a beautiful medium post here.

Is the above example of writing let or const variables in react components good practice?

Regarding this, it is the only practice. Prefer const if your variable is not getting re-assigned, that's the key.

Use of hooks will improve your performance in one way or other as you can do complex work with them instead of writing your own functions, hooks are basically functions that is created at a place and use anywhere. so, you are normally doing function calls and assigning the output to a variable as you do when you call your own functions.

Regarding your example, if you are not re-using otherCondition that don't make a variable out of it, simply use it in your condition like

if (props.isDisabled && props.content.length > 20) { ... }

Why to allocate memory for a single use variable? Other than this, your code looks fine to me.

🌐
Codecademy Forums
discuss.codecademy.com › get help › react.js
What does const mean? - React.js - Codecademy Forums
July 20, 2017 - Hello please answer my so very very difficult question hello. https://www.codecademy.com/courses/react-101/lessons/react-jsx-intro/exercises/jsx-elements-and-surroundings?action=lesson_resume what is wrong with me …
🌐
Javatpoint
javatpoint.com › const-in-reactjs
Const in ReactJS - javatpoint
Const in ReactJS with ReactJS Tutorial, ReactJS Introduction, ReactJS Features, ReactJS Installation, Pros and Cons of ReactJS, Reactnative vs ReactJS, ReactJS Router etc.
🌐
Medium
medium.com › @austinpaley32 › how-to-add-a-constants-file-to-your-react-project-6ce31c015774
How to Add a Constants File to Your React Project | by Austin Paley | Medium
September 17, 2018 - As I’ve been building React projects over the last few weeks, I’ve started to make the transition from making code that simply works to focusing on how I can make my project structure as clean and as to understand as possible. Beyond just basic things like naming variables as clearly as possible, something I’ve been doing recently to clean up each component is to shift all of my constants to their own section of the project.
Top answer
1 of 1
2

There's no way to directly access the variable itself--it doesn't exist outside the function. But there are countless ways to share data between unrelated functions.

In React Components:

In React when you encounter a situation in which multiple components need access to the same state it's usually a sign that you should lift the state up.

So in your example (assuming these are React components) you could do something like this:

// component takes a 'value' prop without caring where it comes from
function ChildA ({ value }) {
  return (
    <div>Child A says {value}</div>
  )
}

// same as above
function ChildB ({ value }) {
  return (
    <div>Child B also says {value}</div>
  )
}

// controls the state and passes it down as a prop
function Parent () {
  const [hello, setHello] = useState('hello');
  return (
    <div>
      <ChildA value={hello} />
      <ChildB value={hello} />
    </div>
  )
}

In javascript more generally

You can follow the same principle, moving shared data up, in javascript generally (non-react):

let hello = 'hello';

function a() {
  console.log(hello);
}

function b() {
  console.log(hello);
}

a(); // logs 'hello'
b(); // logs 'hello'

hello = 'howdy';

a(); // logs 'howdy'
b(); // logs 'howdy'


Using a store with imports/exports

A common pattern for this sort of thing is to use a dedicated "store" class as the source of truth.

I've commented out the imports and exports in the snippet below because they don't make sense in a snippet (and more importantly, they don't work in a snippet).

// HelloStore.js

class HelloStore {
  // keep track of the value internally
  _hello = 'hello';

  // setter
  set hello(newValue) {
    this._hello = newValue;
  }

  // getter
  get hello() {
    return this._hello;
  }
}

const store = new HelloStore();
// export default store;


// Foo.js
// import store from './HelloStore';

function foo () {
  console.log(store.hello);
}


// Bar.js
// import store from './HelloStore';

function bar () {
  console.log(store.hello);
}

foo(); // logs 'hello'
bar(); // logs 'hello'

store.hello = 'howdy'

foo(); // logs 'howdy'
bar(); // logs 'howdy'


Getting change notifications from the store

It's often desirable for components or other code to be alerted to changes to the store value. You can facilitate this by making the store an event emitter.

// This is just a dumber implementation of node's
// event emitter because i can't import it here.
// No reason you'd need to roll your own emitter
// in a real project.
class EventEmitter {
  listeners = [];
  addEventListener (handler) {
    this.listeners.push(handler);
  }
  emit (data) {
    this.listeners.forEach(handler => handler(data));
  }
}

// HelloStore.js

class HelloStore extends EventEmitter {
  // keep track of the value internally
  _hello = 'hello';

  // setter
  set hello(newValue) {
    this._hello = newValue;
    this.emit(newValue); // alert the listeners to the update
  }

  // getter
  get hello() {
    return this._hello;
  }
}

const store = new HelloStore();
// export default store;


// Foo.js
// import store from './HelloStore';

function foo(value) {
  console.log(`foo says ${value}`);
}

function bar(value) {
  console.log(`bar says ${value}`);
}

// register listeners to invoke foo
// and bar when the store value changes
store.addEventListener(foo);
store.addEventListener(bar);

// emits event, triggers listeners
store.hello = 'howdy';

// emits event, triggers listeners
store.hello = 'bonjour';