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
useRef
when you want to manipulate the DOM or grab a changing value. Otherwise use regular variables. Also, mutating auseRef
current value will not cause a re-render. More – Rida