DEV Community

Manish Dnyandeo Salunke
Manish Dnyandeo Salunke

Posted on

Using React.useRef() for Mutable Values

Hey there! Today, we're going to dive deep into one of React's hooks, useRef, and learn how we can use it to work with mutable values. Buckle up, it's going to be a fun ride!

useRef? What's that?

Well, useRef is a hook provided by React that lets you create a 'ref' (reference) to a DOM element or any other value. You can think of it as a way to "remember" something between renders of your component.

Here's how you make a ref:

const awesomeRef = React.useRef(initialValue);
Enter fullscreen mode Exit fullscreen mode

The initialValue bit is optional. If you pass it, the ref will be set to that value initially.

So, what's this about mutable values?

Here's the cool thing: useRef is more than just a way to access DOM elements. You can use it to keep track of a mutable value. What's a mutable value, you ask? It's a value that can change.

The .current property of a useRef is mutable and doesn't cause a re-render when it changes.

Here's a quick example:

function CoolComponent() {
  const renderCount = React.useRef(0);

  React.useEffect(() => {
    renderCount.current = renderCount.current + 1;
  });

  return (
    <div>
      <p>I've rendered {renderCount.current} times.</p>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

In this component, renderCount is a mutable value that sticks around between re-renders. Every time the component renders, useEffect increments renderCount.current by 1. But this doesn't cause a re-render because it's a useRef, not a useState.
When should I use useRef?

You'll find useRef handy when you need to:

  • Get your hands on a DOM element and do stuff with it directly.
  • Keep a value around between re-renders without causing extra renders.

For example, you might use useRef to remember the previous value of a prop or state:

function CoolComponent({ value }) {
  const previousValue = React.useRef();

  React.useEffect(() => {
    previousValue.current = value;
  }, [value]);

  return (
    <div>
      <p>Current value: {value}</p>
      <p>Previous value: {previousValue.current}</p>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

In this component, previousValue remembers the previous value of the value prop. Even though we update previousValue.current in useEffect, it doesn't cause a re-render because previousValue is a ref, not a state.

Wrapping Up

So that's the scoop on useRef and mutable values! It's a nifty way to keep values around between re-renders without causing extra renders, making your components more efficient.

But remember, while useRef is super handy for storing mutable values, it isn't always the right tool for the job. If a change in value should cause a re-render, reach for useState or useReducer instead. Keep coding and exploring!

Top comments (0)