Is it correct to use a regular variable (let, const) in React component?

Viewed 305

I work with React and when I need to create some variable I use for example or:

const [show, setShow] = useState(false);

or:

const canvas = useRef(null);

Are there any situations when I can use instead useState or useRef just regular variable

let a

and make regular assignment? I came across a code in which ordinary variables and ordinary assignments are applied, but it seems to me that this is not correct. Сan I replace let a = useRef(null) with let a = null

4 Answers
  • useState is when you want to re-render the whole component if the state changes
  • useRef is when you want to persist a variable during renders

Other than that, you are free to use let or const

Like when you want to do some logic/calculation and reassign the variable itself.

You can use let yes, but not for your above examples. You shouldn't use it for useState and useEffect etc..

Example of let:

const [show, setShow] = useState(false);
const [otherVar, setOtherVar] = useState(false);
let someVar = 12;
if (otherVar && show) someVar = 20;

return (<Component someProp={someVar} ... />)

You could use a let here, but it's a convention to use const for functions, which is what your examples amount to.

For let it's OK, but usually used when re-render is not wanted.

const is being used much more, and it should be. Because we don't want functionality of component to be overwritten by clumsy assignings.

Related