DEV Community

Kumar Nitesh
Kumar Nitesh

Posted on

Using useRef in ReactJS: A Beginner's Guide

Hi everyone and welcome to my ReactJS tutorial series. In this tutorial, we're going to learn about useRef and how it can be used in React applications.

What is useRef:
The useRef hook is used to access the DOM elements in ReactJS applications. It provides a way to reference a DOM node in our component and keep track of its value between renderings.

Example:
Let's create a simple example to understand how useRef works. We'll create a simple input form and use useRef to focus the input field when the component is rendered.

Code:

import React, { useRef } from 'react';

const Example = () => {
  const inputRef = useRef(null);

  useEffect(() => {
    inputRef.current.focus();
  }, []);

  return (
    <div>
      <input type="text" ref={inputRef} />
    </div>
  );
};
Enter fullscreen mode Exit fullscreen mode

Explanation:
We first import the useRef hook and the useEffect hook from the React library. In our component, we create a constant named "inputRef" using the useRef hook and initialize it with a value of null.

In the useEffect hook, we use the "current" property of the useRef hook to access the input field and call its "focus" method to set the focus on the input field when the component is rendered.

Finally, we return a simple input field with a ref attribute set to our "inputRef" constant.

Conclusion:
That's it for this tutorial on useRef in ReactJS. I hope you have a better understanding of how this hook works and how you can use it in your React applications. If you have any questions, feel free to ask in the comments section below.

Thanks for reading!

Image of Datadog

The Essential Toolkit for Front-end Developers

Take a user-centric approach to front-end monitoring that evolves alongside increasingly complex frameworks and single-page applications.

Get The Kit

Top comments (0)

SurveyJS custom survey software

JavaScript UI Libraries for Surveys and Forms

SurveyJS lets you build a JSON-based form management system that integrates with any backend, giving you full control over your data and no user limits. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay