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?