useRef vs. Regular Variable

I am confused about the differences between the useRef hook and a plain variable inside the component.

Am I right that every component renders, the plain variable also re-renders and persists its value, but the useRef just persists the value and does not re-render?

If that so, what would you recommend between the two?

>Solution :

Here is a sandbox for simulation!

Assuming

let a = 0;
const ref = useRef(0);
const [state,setState] = useState(0);

Now let’s say you use 2 buttons with these click functions

const firstClick = () => {
 a = 2;
 ref.current = 2;
}

const secondClick = () => {
 setState(2);
}

The first click will modify both the ref and the variable.

The Second click will cause a re-render because of a state change.

However if you are printing both ref and variable in a div or text then you will see only ref still persists its value, because React functions form a closure on their variables.

Wherever you need to manipulate Dom or store state without re-rendering on change, ref is your go-to. If you are making logical calculations then go for variables

Leave a Reply