Home > ReactJS > React useRef Hook Tutorial – A Complete Guide

React useRef Hook Tutorial – A Complete Guide

The useRef hook is a powerful tool in the React developer’s toolbox, providing a way to interact with and manipulate the DOM directly.

In this tutorial, we’ll delve into the useRef hook, exploring its use cases and demonstrating how it can be a valuable asset in your React projects.

Understanding useRef

The useRef hook in React is primarily used to create mutable object references that persist across renders. Unlike the useState hook, the useRef hook doesn’t cause a re-render when the value changes, making it perfect for scenarios where you need to store and access mutable values without triggering unnecessary updates.

Create a React Project

Before we dive into the useRef hook, let’s set up a basic React project using Create React App. You can run the following commands to create a react project and start it.

npx create-react-app useRefDemo
cd useRefDemo
npm start

For more detail, you can check the tutorial on how to install reactjs and create an app?

Create useRef Demo Function

Now, let’s create a simple functional component to experiment with the useRef hook.

// src/App.js
import React, { useRef } from 'react';

const useRefDemo = () => {
  const myRef = useRef(null);

  return (
    <div>
      <input ref={myRef} type="text" />
      <button onClick={() => console.log(myRef.current.value)}>
        Log Input Value
      </button>
    </div>
  );
};

export default useRefDemo;

In this example, we’ve created a functional component named useRefDemo. Inside it, we declared a myRef variable using the useRef hook and attached it to an input element. We also added a button that, when clicked, logs the current value of the input field to the console.

Manipulating the DOM with useRef

One of the primary use cases of the useRef hook is to interact with the DOM directly. Let’s explore how useRef can be used to manipulate DOM elements.

// src/App.js
import React, { useRef, useEffect } from 'react';

const useRefDemo = () => {
  const myRef = useRef(null);

  useEffect(() => {
    // Focus on the input field when the component mounts
    myRef.current.focus();
  }, []);

  return (
    <div>
      <input ref={myRef} type="text" />
      <button onClick={() => console.log(myRef.current.value)}>
        Log Input Value
      </button>
    </div>
  );
};

export default useRefDemo;

In this updated example, we’ve added a useEffect hook that runs once when the component mounts. Inside the useEffect, we use myRef.current.focus() to set the focus on the input field, making it an interactive and user-friendly experience.

Conclusion

The useRef hook is a versatile tool in React, allowing developers to interact with the DOM and manage mutable values without causing unnecessary re-renders.

In this tutorial, we explored the basics of the useRef hook, created a simple React project, and demonstrated its use in manipulating the DOM. As you continue to explore React, integrating useRef into your projects will enhance your ability to create efficient and responsive applications.

FAQs

What is the useRef hook in React?

The useRef hook in React is a function that provides a way to create mutable object references that persist across renders. It’s particularly useful for interacting with the DOM and storing mutable values without causing re-renders.

How is useRef different from useState in React?

Unlike useState, the useRef hook doesn’t trigger re-renders when its value changes. It is ideal for scenarios where you need to store and access mutable values without impacting the component’s rendering.

Can useRef be used for DOM manipulation?

Yes, useRef is commonly used for interacting with the DOM directly. You can use it to reference and manipulate DOM elements, such as focusing on an input field, without causing unnecessary re-renders in your React components.

Photo of author

About Aman Mehra

Hey there! I'm Aman Mehra, a full-stack developer with over six years of hands-on experience in the industry. I've dedicated myself to mastering the ins and outs of PHP, WordPress, ReactJS, NodeJS, and AWS, so you can trust me to handle your web development needs with expertise and finesse. In 2021, I decided to share my knowledge and insights with the world by starting this blog. It's been an incredible journey so far, and I've had the opportunity to learn and grow alongside my readers. Whether you're a seasoned developer or just dipping your toes into the world of web development, I'm here to provide valuable content and solutions to help you succeed. So, stick around, explore the blog, and feel free to reach out if you have any questions or suggestions. Together, let's navigate the exciting world of web development!

Leave a Comment