How to declare a variable inside a functionnal component in ReactJS

Viewed 135

I have a variable "myVar" (NOT A STATE)

const myComponent = () => {
  const [myState, setMyState] = useState(true)
  const myVar = false

  return <button onClick={() => {myVar = true} >Click here</button>

}

As it is written, when the component is re-rendered, then myVar is re-initialized... I want to have the variable keep its previous value. How can I get this behavior?

Solutions I found are:

SOLUTION 1 : Initialise the variable outside of the component (but not in the component scope)

let myVar = 'initial value';
const myComponent = () => {
  ....
  // myVar is updated sometimes when some functions run
}

SOLUTION 2 : declare a component prop (but public)

const myComponent = ({myVar = true) => {
  ....
}

What is the recommended way to solve this problem?

2 Answers

React docs suggest to use useRef to keep an arbitrary mutable value around. So, you could do this:

// set ref
const myValRef = React.useRef(true);

// ...

// update ref
myValRef.current = false;

You want to use solution #1.

The code

let myVar = 'initial value';
const myComponent = () => {
  ....
  // myVar is updated sometimes when some functions run
}

will keep the variable myVar between renders.

The 2nd solution will not work. The variable as a prop doesn't maintain the state between renders.

Related