DEV Community

Cover image for Simplifying React Hooks: useRef πŸ’―
Ali Samir
Ali Samir

Posted on

4

Simplifying React Hooks: useRef πŸ’―

Introduction

When working with React, useRef is a powerful hook that allows you to access and persist values across renders without causing re-renders. This makes it an essential tool for handling DOM references, persisting state, and optimizing performance.

This article will break down useRef, explore its use cases, and demonstrate best practices for using it effectively in TypeScript projects.


Understanding useRef πŸ”₯

The useRef hook is a built-in React hook that returns a mutable object with a .current property. Unlike state variables created with useState, modifying useRef does not trigger re-renders.

Syntax

const ref = useRef<T>(initialValue);
Enter fullscreen mode Exit fullscreen mode
  • T is the type of the referenced value.

  • initialValue is the initial value of .current.

Example:

import { useRef } from "react";

const inputRef = useRef<HTMLInputElement | null>(null);
Enter fullscreen mode Exit fullscreen mode

Common Use Cases βš™οΈ

1. Accessing and Manipulating DOM Elements

A frequent use case for useRef is accessing DOM elements without triggering re-renders.

import { useRef } from "react";

const FocusInput = () => {
  const inputRef = useRef<HTMLInputElement>(null);

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

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

export default FocusInput;
Enter fullscreen mode Exit fullscreen mode

Explanation:

  • The inputRef refers to the <input> element.

  • Calling inputRef.current?.focus() sets focus on the input field.


2. Persisting Values Without Re-Renders

useRef is useful for persisting values that don’t trigger re-renders, such as timers, previous values, or component lifecycles.

import { useEffect, useRef, useState } from "react";

const Timer = () => {
  const [count, setCount] = useState(0);
  const intervalRef = useRef<NodeJS.Timeout | null>(null);

  useEffect(() => {
    intervalRef.current = setInterval(() => {
      setCount((prev) => prev + 1);
    }, 1000);

    return () => {
      if (intervalRef.current) clearInterval(intervalRef.current);
    };
  }, []);

  return <p>Timer: {count} seconds</p>;
};

export default Timer;
Enter fullscreen mode Exit fullscreen mode

Explanation:

  • The intervalRef persists the interval ID.

  • It prevents unnecessary re-renders while ensuring the timer can be cleared when needed.


3. Storing Previous Values

We can use useRef to store the previous state value before a component re-renders.

import { useEffect, useRef, useState } from "react";

const PreviousValue = () => {
  const [count, setCount] = useState(0);
  const prevCountRef = useRef<number>(count);

  useEffect(() => {
    prevCountRef.current = count;
  }, [count]);

  return (
    <div>
      <p>Current: {count}</p>
      <p>Previous: {prevCountRef.current}</p>
      <button onClick={() => setCount(count + 1)}>Increment</button>
    </div>
  );
};

export default PreviousValue;
Enter fullscreen mode Exit fullscreen mode

Explanation:

  • prevCountRef.current stores the previous count.

  • Even after re-renders, it retains the previous state value.


Best Practices for useRef πŸ’―

1- Use useRef for Non-Rendering Data: Avoid using it for state management that affects UI.

2- Use TypeScript to Ensure Safety: Always define proper types to avoid null or undefined errors.

3- Remember That useRef Doesn’t Trigger Re-Renders: Update .current only when necessary.

4- Avoid Overuse: If a value needs to trigger a re-render, useState is the better option.


Conclusion βœ…

The useRef hook is an essential tool for optimizing React applications. Whether accessing DOM elements, persisting values, or handling timers, it provides performance benefits by preventing unnecessary re-renders.

By combining useRef with TypeScript, you can write safer and more maintainable React applications.


🌐 Connect With Me On:

πŸ“ LinkedIn
πŸ“ X (Twitter)
πŸ“ Telegram
πŸ“ Instagram

Happy Coding!

PulumiUP 2025 image

From Infra to Platforms: PulumiUP 2025 Panel

Don’t miss the expert panel at PulumiUP 2025 on May 6. Learn how teams are evolving from infrastructure engineering to platform engineeringβ€”faster, more secure, and at scale.

Save Your Spot

Top comments (0)

Image of Stellar post

Check out Episode 1: How a Hackathon Project Became a Web3 Startup πŸš€

Ever wondered what it takes to build a web3 startup from scratch? In the Stellar Dev Diaries series, we follow the journey of a team of developers building on the Stellar Network as they go from hackathon win to getting funded and launching on mainnet.

Read more

πŸ‘‹ Kindness is contagious

Engage with a wealth of insights in this thoughtful article, valued within the supportive DEV Community. Coders of every background are welcome to join in and add to our collective wisdom.

A sincere "thank you" often brightens someone’s day. Share your gratitude in the comments below!

On DEV, the act of sharing knowledge eases our journey and fortifies our community ties. Found value in this? A quick thank you to the author can make a significant impact.

Okay