How to use React useRef Hook

React provides a powerful hook called useRef that allows you to interact with the DOM directly and persist values across renders without triggering a re-render. In this blog post, we’ll explore the use cases of useRef and how it can be applied in a real-world example.

What is useRef?

useRef is a Hook in React that provides a mutable object called a ref object. This object has a .current property which can be assigned any value. The key feature of useRef is that it persists across renders and does not cause the component to re-render when the ref object changes.

Use Cases of useRef

  1. Accessing DOM Elements

One common use case of useRef is accessing and interacting with DOM elements directly. Let’s consider an example where we want to focus on an input field when the component mounts.

2. Storing Previous Values

Another use case is storing values that need to persist across renders without triggering re-renders. This is particularly useful for comparing previous and current values.

Real-World Example: Auto-Expanding Textarea

Let’s create a real-world example to showcase the power of useRef. We’ll build an auto-expanding textarea that dynamically adjusts its height based on the content. This is a common feature in messaging applications.

Step 1: Set Up Your React App

If you haven’t already, create a new React app using create-react-app:

npx create-react-app auto-expanding-textarea
cd auto-expanding-textarea

Step 2: Create AutoExpandingTextarea Component
Create a new component named

AutoExpandingTextarea.js:

// src/components/AutoExpandingTextarea.js
import React, { useRef, useState } from "react";
const AutoExpandingTextarea = () => {
  const textareaRef = useRef(null);
  const [content, setContent] = useState("");
  const handleInput = () => {
    const textarea = textareaRef.current;
    textarea.style.height = "auto";
    textarea.style.height = `${textarea.scrollHeight}px`;
  };
  return (
    <textarea
      ref={textareaRef}
      value={content}
      onChange={(e) => setContent(e.target.value)}
      onInput={handleInput}
      placeholder="Type your message..."
    />
  );
};

export default AutoExpandingTextarea;

In this example, we use useRef to access the textarea element directly. The handleInput function is called on every input change, adjusting the height of the textarea based on its content.

Step 3: Integrate AutoExpandingTextarea

Integrate the AutoExpandingTextarea component into your App.js:

import React from 'react';

import AutoExpandingTextarea from './components/AutoExpandingTextarea';

function App() {
return (

<div className="App">

	<h1>Auto-Expanding Textarea Example</h1>

	<AutoExpandingTextarea />

</div>

);

}


export default App;

Step 4: Run Your App

Start your React app:

npm start

Visit http://localhost:3000 in your browser, and you’ll see the auto-expanding textarea in action.

Conclusion

In this blog post, we explored the useRef hook in React with a real-world example of building an auto-expanding textarea. useRef is a versatile tool that opens the door to many possibilities, including direct DOM manipulation and persisting values across renders. Understanding when and how to use useRef can greatly enhance your ability to create dynamic and interactive React components. Feel free to experiment with useRef in your projects to discover its full potential.

Please do not post any spam link in the comment box😊

إرسال تعليق (0)
أحدث أقدم