DEV Community

Cover image for Understanding The useRef React Hook 🔥
Ali Samir
Ali Samir

Posted on

Understanding The useRef React Hook 🔥

React's useRef hook is a versatile tool that allows you to persist values across re-renders.

Unlike useState, changes to a useRef value won't trigger a component re-render, making it ideal for scenarios where you need to access or manipulate DOM elements directly, store data without affecting the render process, or create mutable objects that persist between renders.

In this post, we'll explore the useRef hook in detail, providing practical examples in TypeScript.


📌What is useRef?

The useRef hook returns a mutable reference object. This object has a single property, current, which can be modified directly. The value of current persists between renders, making it different from state managed by useState.

import { useRef } from 'react';

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

📌Common Use Cases

1. Accessing DOM Elements

One of the primary use cases for useRef is to access DOM elements directly. This can be useful for focusing elements, setting scroll positions, or triggering animations.

import { useRef, useEffect } from 'react';

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

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

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

2. Storing Data Without Re-renders

If you need to store data that doesn't affect the component's rendering, useRef is a good choice.

import { useRef } from 'react';

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

  const increment = () => {
    countRef.current++;
    console.log(countRef.current); // This won't trigger a re-render
  };

  return (
    <div>
      <button onClick={increment}>Increment</button>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

3. Creating Mutable Objects

You can use useRef to create mutable objects that persist between renders. This can be useful for complex state management scenarios or when you need to share data between components.

import { useRef } from 'react';

function MyComponent() {
  const dataRef = useRef({ count: 0 });

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

  return (
    <div>
      <button onClick={increment}>Increment</button>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

📌Important Considerations

  • Avoid excessive DOM manipulations: While useRef allows you to access DOM elements, excessive manipulations can impact performance. Use it judiciously.

  • Prefer state for UI updates: If you need to update the UI based on a value, use useState instead of useRef.

  • Understand the difference between useRef and useState: While both hooks can store values, their purposes and behaviors differ significantly.


Conclusion ✅

The useRef hook is a powerful tool in your React toolkit.

By understanding its core concepts and use cases, you can effectively manage complex state and interactions within your components.

Remember to use it wisely and consider the alternatives for specific scenarios.

Happy Coding!

Top comments (0)