Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should const be outside function components in React.js?

Some of my code got a review comment saying something like "move const outside the function to avoid redeclaration". This was a normal function component, something like this:

export default function someComponent() {
  const someString = 'A string';
  ///...
}

I was confused about the idea of this causing a redeclaration, because it does not, I know that the record that holds the variables and constants belong to the scope, so it's not exactly that. But then i remembered that typescript does not allows you to have a const inside a class, not sure about the reason or is this is related. But then ts added the readonly modifier in ts v2, so the confusion remains.

Should const be outside function components, or not? I would love to know more opinions.

like image 644
Eduardo Oviedo Blanco Avatar asked Jan 28 '26 07:01

Eduardo Oviedo Blanco


1 Answers

There are 2 sides to the coin. Firstly, in terms of clean code and readability, I strongly prefer local declarations like in your example. I would love using more nested functions as well.

However, in JavaScript, every time the function executes, the local definitions will be redeclared, even if they are constants or functions. So it's a trade-off. If the function is called many times, this becomes an overhead.

I think it would not be hard for a compiler like TypeScript's tsc or some other pre-processor to extract those definitions at compile time to have best of both worlds. But it's likely that they do not do this to remain fully compatible. I am not aware of such tools but would be interested if there are some.

like image 106
vitoke Avatar answered Jan 29 '26 21:01

vitoke