useRef Hook in React

useRef Hook in React

React has a really useful hook called useRef. In some ways, it is similar to the useState hook because it can be used for tracking values. However, useRef is different in that it doesn't cause re-renders like useState. useRef can be used for other cases, such as manipulating DOM elements. For example, you can focus on an input field when a component mounts (more on that later). Overall, it’s a great tool for various use cases. Let’s learn how it actually works and go through a few code examples.

Using useRef

At first, it might be hard to grasp how useRef actually works, but once understood, it is really easy to use. Let’s start with the basics.

To use this hook, you first need to import it, just like you would import useState and other hooks:

Then you need to define the initial value:

In this case, we want to manipulate an element, so we need to reference it:

We want to focus on an element when the component mounts, so let's call the ref inside the useEffect hook:

The current property always holds the value of the useRef hook, allowing you to access it. The focus method helps us focus on the element.

This is a basic example of how useRef functions.

Key Points to Know Before Using useRef

  1. Initial Value: You can define any initial value you need.

  2. Accessing useRef Value: To access the useRef value, you need to use the current property.

  3. No Re-renders: useRef never causes a re-render.

  4. DOM Manipulation: In this example, we used focus, but there are many more DOM methods you can use, such as click, scrollIntoView, etc.