Using useRef in React
Tags: react, javascript, webdev, beginners
Published: 2024-04-20 12:11:45

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.

```
import React, { useRef } from 'react';

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

  const handleButtonClick = () => {
    if (inputRef.current) {
      console.log('Input value:', inputRef.current.value);
    }
  };

  return (
    <div>
      <input type="text" ref={inputRef}  />
      <button onClick={handleButtonClick}>Get Input Value</button>
    </div>
  );
}

export default refExample;
```

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.

```
import React, { useState, useEffect, useRef } from 'react';

function CachedDataComponent() {
  const [posts, setPosts] = useState(null);
  const cacheRef = useRef({}); // Önbellek nesnesini useRef ile oluşturuyoruz

  useEffect(() => {
    const fetchData = async () => {
      // API isteği yapmadan önce önbellekte kontrol ediyoruz
      if (cacheRef.current['cachedData']) {
        setPosts(cacheRef.current['cachedData']);
      } else {
        try {
          const response = await fetch('https://jsonplaceholder.typicode.com/posts');
          const jsonPostData = await response.json();
          cacheRef.current['cachedData'] = jsonPostData; // API verisini önbelleğe alıyoruz
          setPosts(jsonPostData);
        } catch (error) {
          console.error('API Hatası:', error);
        }
      }
    };

    fetchData();
  }, []);

  return (
    <div>
      <h1>Önbelleğe Alınmış Veri</h1>
      {posts ? (
        <ul>
          {posts.map((post) => (
            <li key={post.id}>{post.title}</li>
          ))}
        </ul>
      ) : (
        <p>Postlar yükleniyor...</p>
      )}
    </div>
  );
}

export default CachedDataComponent;
```

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…