Subscribe
How to use the useRef hook in React
4 mins read

By: vishwesh

How to use the useRef hook in React

If you're new to React, you might be wondering how to access the DOM elements in your components. One way to do this is by using the useRef hook. In this article, we'll explore what the useRef hook is, why you might want to use it, and how to use it in your React components.

What is the useRef hook?

The useRef hook is a built-in React hook that allows you to create a mutable reference that persists between renders. You can use it to access the DOM elements in your components, store any mutable value, or even create a counter. It returns an object with a single property called current, which you can use to access the value of the reference.

Why use the useRef hook?

There are many use cases for the useRef hook in React, but the most common one is to access the DOM elements in your components. If you need to manipulate a DOM element, such as setting the focus or changing the value, you can use the useRef hook to create a reference to that element.

Another use case for the useRef hook is to store any mutable value that you want to persist between renders. For example, you can use it to store the previous value of a prop or state and compare it with the current value to detect changes.

How to use the useRef hook?

Using the useRef hook is straightforward. You start by importing it from the react module:

import { useRef } from 'react';

Then, you can use it in your functional component by calling the useRef function and passing an initial value:

function MyComponent() {
  const myRef = useRef(initialValue);
  // ...
}

In the example above, myRef is the mutable reference that persists between renders, and initialValue is the initial value of the reference. You can omit the initial value if you don't need it.

Accessing DOM elements

To access a DOM element with the useRef hook, you need to create a reference to that element by adding a ref attribute to it:

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

  function handleClick() {
    inputRef.current.focus();
  }

  return (
    <div>
      <input type="text" ref={inputRef} />
      <button onClick={handleClick}>Focus input</button>
    </div>
  );
}

In the example above, we create a reference to the input element by adding the ref attribute with the inputRef reference. We also define a function called handleClick that sets the focus to the input element by calling the focus method on the current property of the reference.

Storing mutable values

To store a mutable value with the useRef hook, you can simply assign it to the current property of the reference:

function MyComponent() {
  const prevValueRef = useRef(null);
  const [value, setValue] = useState('');

  useEffect(() => {
    prevValueRef.current = value;
  }, [value]);

  return (
    <div>
      <p>Current value: {value}</p>
      <p>Previous value: {prevValueRef.current}</p>
      <input type="text" value={value} onChange={(e) => setValue(e.target.value)} />
    </div>
  );
}

In the example above, we create a reference called prevValueRef to store the previous value of the value state. We update the reference in the useEffect hook by assigning the current value of value to the current property of the reference. We also display the current and previous values in the component by accessing the current property of the reference.

Creating a counter

You can also use the useRef hook to create a counter that persists between renders:

function MyComponent() {
  const countRef = useRef(0);

  function handleClick() {
    countRef.current++;
    console.log(`Count: ${countRef.current}`);
  }

  return (
    <div>
      <button onClick={handleClick}>Increment count</button>
    </div>
  );
}

In the example above, we create a reference called countRef with an initial value of 0. We also define a function called handleClick that increments the value of the reference by 1 and logs it to the console. We call the handleClick function when the button is clicked.

Conclusion

In this article, we explored what the useRef hook is, why you might want to use it, and how to use it in your React components. We covered several use cases for the useRef hook, including accessing DOM elements, storing mutable values, and creating a counter. Remember that the useRef hook returns an object with a single property called current, which you can use to access the value of the reference. By using the useRef hook, you can make your React components more powerful and flexible.

Recent posts

Don't miss the latest trends

    Popular Posts

    Popular Categories