In addition to storing DOM references, the useRef hook can be used to store values without re-rendering the component.
If you have a class component that stores and manipulates values using instance variables like this:
class YourComponent extends React.Component {
constructor() {
this.count = 0;
}
onClick(e) {
this.count++;
}
// ...
}
You can simulate this behavior with the useRef
hook:
function YourComponent() {
const countRef = useRef(0);
function onClick() {
countRef.current++;
}
// ...
}
In both cases, when the onClick
handler is called and either this.count
or countRef.current
are updated, the component will not re-render.
This can be useful when needing a way to keep track of values for logging or other purposes that don't involve rendering data to the screen.
Jamund Ferguson: [0:00] In our RateTable, let's create a new ref. Type const countRef = useRef(), and then pass in, as the default value, . We're going to use this counter to count any time that our bounce() method is called. At the bottom of our bounce method, we can type countRef.current++. It will simply increment the value by 1.
[0:21] An interesting property of refs is that you can always change them without re-rendering your component. I'm going to type console.log("count", countRef.current). As I open my console, we can see what happens when our bounce method gets called. You can see that count is -- that was the first time, it uses the default value -- but even as we hover over it multiple times, the count displayed never changes.
[0:44] That's simply because our function isn't re-rendered each time we update our ref. However, if we move the count into our bounce function and hover over, you can see that it is being updated each time.
[0:57] Using a ref like this is similar to how one might had used an instance variable in the past. It might have said something like this.counts = , and then later, this.counts++. That might be something you'd use for analytics or logging or anything that doesn't require re-rendering the page.
[1:15] Instead of using instance variables, we can use refs to achieve the same goal.
Member comments are a way for members to communicate, interact, and ask questions about a lesson.
The instructor or someone from the community might respond to your question Here are a few basic guidelines to commenting on egghead.io
Be on-Topic
Comments are for discussing a lesson. If you're having a general issue with the website functionality, please contact us at support@egghead.io.
Avoid meta-discussion
Code Problems?
Should be accompanied by code! Codesandbox or Stackblitz provide a way to share code and discuss it in context
Details and Context
Vague question? Vague answer. Any details and context you can provide will lure more interesting answers!