Replacing Instance Variables with the useRef Hook

Jamund Ferguson
InstructorJamund Ferguson

Share this video with your friends

Send Tweet

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) {
  // ...

You can simulate this behavior with the useRef hook:

function YourComponent() {
  const countRef = useRef(0);
  function onClick() {
  // ...

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.