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!

Oldest comments (0)