What is useRef for? When should I use it?
useRef is like a box where you can store something. A number, an object, anything you want.
This value is persisted between renders. So if you save in this box some value, it will be available in the next render.
And unlike useState, changes in your useRef "box" does not trigger a new render.
Some comparisons (not technical):
-
It is similar to useState, but it doesn't triggers a new render.
-
If you come from class components, it is like storing an instance variable (this.value = someValue).
What is it used for?
-
to store mounted components: <Input ref={myRef} /> so you can later do something. For example, trigger a focus on this element: myRef.current.focus()
-
To store anything you want (like useState) BUT without triggering a new render.
I wrote about this here.
More on reddit.comreactjs - Why does 'useRef' exist? What's it intended for? - Stack Overflow
Understanding React's useRef Hook
How to replace useState with useRef and be a winner
Videos
Hi! I'm currently learning the hooks i haven't used before, useRef is specifically hard for me to understand, What is it for? and when should I use it? I tried reading the docs over and over again and watching web dev simplified and Ben awads vids but I still don't understand it. Can anyone ELI5?
useRef is like a box where you can store something. A number, an object, anything you want.
This value is persisted between renders. So if you save in this box some value, it will be available in the next render.
And unlike useState, changes in your useRef "box" does not trigger a new render.
Some comparisons (not technical):
-
It is similar to useState, but it doesn't triggers a new render.
-
If you come from class components, it is like storing an instance variable (this.value = someValue).
What is it used for?
-
to store mounted components: <Input ref={myRef} /> so you can later do something. For example, trigger a focus on this element: myRef.current.focus()
-
To store anything you want (like useState) BUT without triggering a new render.
I wrote about this here.
useRef is used when you want to track a value that's unique to a component instance but you don't want React to necessarily be notified when it updates.
The main reason to use it would be to keep track of a DOM element or to keep track of the previous props for comparisons sake.
These weren't necessary when we used class components because you could assign values to the instance of the class and React wouldn't track them, but in functions we can't use instance variables, hence Refs.
One of the downsides of React.useState() is that updating a state value results in the component re-rendering and that can sometimes be undesirable.