How To Use useRef Hook In React? See Example

What Is useRef Hook?

The useRef hook allows you to access DOM elements directly or store mutable values that persist across renders without causing re-renders.


Basic Syntax

const refContainer = useRef(initialValue);
  • refContainer → object with current property
  • initialValue → starting value

Example 1: Accessing DOM Element

import React, { useRef } from "react";

function InputFocus() {
  const inputRef = useRef();

  const handleFocus = () => {
    inputRef.current.focus();
  };

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

Example 2: Persisting Values Without Re-render

function Timer() {
  const count = useRef(0);

  const increment = () => {
    count.current += 1;
    console.log(count.current);
  };

  return <button onClick={increment}>Increase Count</button>;
}

When To Use useRef

  • Access DOM elements directly
  • Store values that don’t trigger re-render
  • Maintain previous values between renders
  • Manage timers or subscriptions

Conclusion

The useRef hook is versatile for direct DOM access and persistent mutable values, helping build dynamic React apps efficiently.


Citations

https://savanka.com/category/learn/react/
https://www.w3schools.com/REACT/DEFAULT.ASP

Leave a Comment

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *