The useRef() hook
Published: 2024-02-27 12:05:43

## Introduction

I have been learning about React hooks for some time now, and some of them can be a bit confusing to understand (looking at you useState! 🙄), while some are more straight forward to grasp. In this article, I want to share what I have learnt about the useRef() hook, and how it can be useful in your project.

## What is the useRef() hook?

The useRef() hook is a built-in React hook used to store data you want your component to remember that does not re-render your application. Notice I said **"That does not re-render your application"**, this is very important to understand because useRef() kind of works like useState(), only that changes made to a value created with useRef() does not cause your application to re-render. When your component first mounts, React stores the value of the Reference in memory but doesn't keep track of it after that, this is what helps the ref to still be accessible even when the component re-renders. Calling the useRef() hook passes a reference (ref) to your component, which helps the component preserve any data stored in that reference. This ref is a plain JS object, which is represented with this syntax

```js
{
  current: initialValue;
}
```

This initialValue can be any JS primitive data type such as numbers, arrays, strings, objects etc.

Here is a basic example of how useRef() is used

```js
import { useRef, useState } from "react";

function App() {
  const [count, setCount] = useState(0);
  const ref = useRef(0);

  function handleIncrement() {
    setCount((count) => count + 1);
  }

  function handleDecrement() {
    setCount((count) => count - 1);
  }

  return (
    <>
      <h3>Count: {count}</h3>
      <button onClick={handleIncrement}>Increment count</button>
      <button onClick={handleDecrement}>Decrement count</button>

      <p>Reference value: {ref.current}</p>
    </>
  );
}

export default App;
```

When the counter updates, the component will re-render to show that value. Since we created a ref with the value 0, that value will still be there no matter how many times the component re-renders. If we had used variables instead of a reference, any changes made to those variables will not reflect when the component re-renders because React does not keep track of those changes (React only keeps track of changes made to the state). This can be frustrating if you are trying to persist data as the component re-renders, that's why the useRef() hook is used in this kind of situations, to preserve changes that need to persist as the application re-renders, preventing any loss of information!.

```js
function App() {
  let count = 0;

  const incrementCount = () => {
    count++;
  };

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={incrementCount}>Increment</button>
    </div>
  );
}

export default App;
```

No matter how many times you click the Increment button, count will never increment because React is not aware the data stored in that variable has changed, React will only update the UI when the state has changed.

The useRef() hook is also used to target specific HTML elements in the DOM (This is the most common use case for it). Recall that in JS, when we want to access a DOM element, we would use DOM selectors such as document.querySelector(), document.getElementById() etc. With the useRef() hook, we can do the same thing in React since we don't access DOM elements directly. Here is how to store a reference to a specific element using the useRef() hook.

```js
import { useRef } from "react";

function App() {
  const inputRef = useRef(null);

  return (
    <>
      <input ref={inputRef} />
    </>
  );
}

export default App;
```

### Warning!

Don't use useRef() to store state values that affect the rendering of your application, it is only meant for storing references to values or DOM elements that need to be accessible to as the component re-renders as shown above. your React application is not aware of any changes made to a ref, so if you use a ref to store the state of your application, how will React know the state has changed?.

## Conclusion

There is still a bit more to the useRef hook, but this what I have learnt about it so far, it's a very useful hook, just be careful with how you use it so that your application doesn't break. Expect more React hook articles like this, and if you read till the end, hope you found this useful. You can follow me on [Twitter](https://twitter.com/kansoldev), [Github](https://github.com/Kansoldev) and [Linkedin](https://linkedin.com/in/oyinkansola-yahaya)