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?
CodePudding user response:
Variable declared using useRef
doesn't get included in the react life cycle which means if any state updates the value defined using useRef
doesn't change that's the advantage.Whereas variable declared without using useRef
gets reclared upon component re-render.
There is an alternate approach to solve the issue, as that will pollute the global space which may cause unexpected things The approach is to declare variable outside the component.
CodePudding user response:
If you need some data to be stored and changed, use state. (for example tracking input value, some opened\closed states of modal windows etc.)
If you need some data to be calculated and displayed, use variables.
(imagine you have filters, and some data that needs to be filtered, filters will be stored in some state variable, and you might want to create a variable filteredData
that needs to be calculated every re-render)
In case if you need to manipulate DOM, or use some value outside of react lifecycle, use refs. (for example you need to have previous value of your state variable, or for some reason destroy some component or change it styles)
CodePudding user response:
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