How to set a variable in React/TS

  javascript, reactjs, typescript

Part 2 of wanting to absolutely die while learning React/TS.

So I’m in some code that looks like this.
Basically I’ve tried in 3 different ways to set a variable.

  1. Closure. It doesn’t work. This is really a remarkable feat of engineering to break JS basics like this. Literally every single line of code is encapsulated in this React.FC function and that doesn’t seem to matter.
  2. useRef. It seems to work but why do I need this to set a variable.
  3. useState. Pretty sure this is for the DOM and not simple flags.

So here it is. 20k hours of Javascript under my belt and I cannot set a variable in React/TS.

const MyElement: React.FC = () => {
  // This one suffers from scope issues, somehow. 
  let currentRow1: HTMLElement | null;
  // I guess this works but God does it feel wrong
  const currentRow2 = React.useRef<null | HTMLElement>(null);
  // Pretty sure this is for DOM rendering anyway
  const [currentRow3, setCurrentRow3] = React.useState<null | HTMLElement>(null)
  // Here's a handler for an event
  const handleClickEvent = () => {
    // Ok closure works here..? huh
    currentRow1 = somelement
    // This works, but why would I want to do this
    currentRow2.current = somelement
    // At least I'm pretty sure this is not what this is for

  const unsetCurrentRow = () => {
     if(currentRow1) // Undefined!!!
        currentRow1 = null;
     currentRow2.current = null; // Yes
     // Again, most likely wrong altogether 

So I feel like I’m taking crazy pills. Do I not understand TS or do I not understand React? Why doesn’t closure work? Why am I forced to use an object that has a property called current? What the heck am I doing?

Source: Ask Javascript Questions