Using useRef in React

Using useRef in React

Hello, friends! In this article, I will explain what the useRef hook is in React applications and how to use it. If you’re ready, let’s get started.

What is useRef?

In React applications, the useRef hook is used to access DOM elements and to store the previous value of states. It is especially useful for scenarios like getting the value of input fields or storing the previous value.

1- Basic Usage (Reference)

Explaining basic usage with an example would be more illustrative.

Let’s start by creating a simple component and adding an input and a button inside it. Then, let’s import the useRef hook from the React library, and using this hook, create an inputRef reference. Next, let's attach it to the input element. Now, let's define a function for the button that logs the value of the inputRef variable to the console.

One thing to note here is that in some cases, inputRef.current might be null. This could happen if the DOM element has not yet been created or has been deleted. Therefore, we first check if this value exists, and if it's not null, we log the current value of inputRef to the console.

As you can see, our component is this simple. When tested, we can see the value we entered in the input field in the console using the button.

2- Storing Previous Values

If we explain this usage with another example, we want to cache the value returned from an API request using useRef. This way, we prevent the component from making the same API request repeatedly when it’s re-rendered.

Just like before, we import the useRef, useEffect, and useState hooks from the React library. Then, we create a simple list view and initialize a posts state that starts as empty. When the component is first rendered, useEffect will run. If we don't have a cacheData ref, we send an API request and cache the result using cacheRef.current['cachedData'] = jsonPostData. Later, to present the data to the user in a list view, we set the posts state. From then on, if the component is re-rendered, it will check if there's cached data. If there is, it will set the state with that value. If not, it will make an API request and cache the result.

In summary, we’ve created a caching object using the useRef hook to store API data. If the cached data exists in previous requests, it’s used directly; otherwise, we retrieve the data from the API and store it in the cache. This way, we achieve our goal, and we have the same data without the need to repeatedly send API requests.

Conclusion

So, friends, after a long break, I wanted to address a simple yet important topic for you. I hope I haven’t made any mistakes in my explanation or in the content. If you find any errors, please don’t hesitate to let me know. You can also leave your questions in the comments or reach out to me at tariqkaya24@gmail.com.

Thank you all very much.

Until the next article…