# How to use React.useRef hook

According to the [React docs](https://react.dev/reference/react/useRef):

> `useRef` is a React Hook that lets you reference a value that’s not needed for rendering.

Here are two examples where `useRef` should be used:

* Referencing a value with a ref
    
* Manipulating the DOM with a ref
    

# Referencing a value with a ref

The most common example of referencing a value would be either [`setTimeout`](https://developer.mozilla.org/en-US/docs/Web/API/setTimeout) or [`setInterval`](https://developer.mozilla.org/en-US/docs/Web/API/setInterval).

`setInterval` is a global javascript function that will call a callback function at a defined interval. When you initialise the interval function, it will continue running until you call `clearInterval`.

```javascript
const intervalId = setInterval(callback, 1000);
```

To clear the interval, you will need to use the returned `intervalId`.

```javascript
clearInterval(intervalID);
```

In a React component, you will need to retain `intervalId` between renders. By using `useRef`, the component can store the `intervalId` until it clears the interval.

%[https://codepen.io/callumm/pen/wvRBvrN?editors=0010] 

# Manipulating the DOM with a ref

It is bad practice to directly manipulate the DOM in React. It can cause performance issues and unexpected side effects. However, you may need to use a library that needs to access the DOM.

As an example, let's say you decide to use the library [AnimeJs](https://animejs.com/) to add javascript animations to your application. However, AnimeJs is a vanilla javascript library, so we will need to find a way to integrate it into the React application.

The documentation provides the following basic example of an animation.

```javascript
anime({
  targets: '.css-selector-demo .el',
  translateX: 250
});
```

To integrate this code with React, we can very easily replace the targets with `useRef`. First, initialise `useRef` within the component.

```javascript
const element = React.useRef(null);
```

Next, pass `element` into the relevant element.

```javascript
<div ref={element}></div>
```

Finally, update the animation call to reference `element.current`. The `current` property holds a reference to a value that persists across re-renders of the component.

```javascript
anime({
  targets: element.current,
  translateX: 250
});
```

Below is a working example with AnimeJs.

%[https://codepen.io/callumm/pen/KKbwPRx] 

# Conclusion

Hopefully, you should now have a good understanding of when and how you should use the `useRef` hook.
