Declare a variable inside a functional component in ReactJS

Viewed 1130

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 you know, this way, if an other state change, the component is re-render, then "myVar" is re-initialized...

Below, solutions I found...

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

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

SOLUTION 2 : declare a component prop (but public)

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

What is the regular solution ?

2 Answers

Use the useRef hook. The value stored by the reference will not be reinitialized during a re-render. Changing the value stored by the reference will not trigger a re-render, as it is not a state change.

Ok, in a class component, this can be resolved by the componentDidMount & the componentDidUpdate logics. Same behavior can be done with functional component by using the useRef & the useEffect hooks:

const myComponent = () => {
      const mounted = useRef();
    
    useEffect(() => {
        if (!mounted.current) {
           // do componentDidMount logic
            mounted.current = true;
            const myVar = false
        } else {
          // do componentDidUpdate logic
        }
      });
    }
Related