Ora

Should I Use Refs in React?

Published in React Refs Usage 4 mins read

Yes, you should use refs in React when you need to directly interact with a DOM element or an instance of a component in situations where standard data flow (props and state) is insufficient or impractical. Refs provide a way to access the underlying DOM nodes or React component instances, serving as an "escape hatch" from React's typical declarative approach.

What are Refs in React?

Refs, short for "references," are a feature in React that allow you to obtain a direct reference to a DOM element or a class component instance rendered by React. They are primarily used for imperative actions that cannot be easily achieved through declarative state updates.

A key benefit of using refs is that they enable you to reference certain information within a component without that information triggering new renders. This can be particularly useful for performance-sensitive operations or direct manipulations.

When to Use Refs

Refs are most appropriate for side effects or direct interactions that fall outside the typical React data flow. Here are the common scenarios where using refs is beneficial:

  • Managing Focus, Text Selection, or Media Playback: You can use refs to programmatically focus an input field, select text in a text area, or control video/audio playback (e.g., play, pause, seek).
    • Example: Automatically focusing an input field when a component mounts.
  • Triggering Imperative Animations: For complex animations that involve direct manipulation of DOM properties or integration with third-party animation libraries, refs provide the necessary handle to the DOM element.
  • Integrating with Third-Party DOM Libraries: When working with libraries that directly manipulate the DOM (e.g., D3.js, jQuery plugins), refs allow you to pass the DOM node to these libraries.
  • Measuring DOM Element Dimensions or Position: If you need to know the width, height, or position of a DOM element for layout calculations, refs give you direct access to the element's properties.

When to Avoid Refs

While powerful, refs should be used sparingly. Most interactions and updates in React applications should be handled via the declarative system of props and state. Avoid using refs for:

  • Declarative UI Updates: If something can be achieved by updating the component's state, which then re-renders the component with new props, that is almost always the preferred approach.
  • Controlling Component Lifecycle: React's lifecycle methods and hooks (like useEffect) are designed for managing component behavior over time.
  • General Data Flow: Passing data between components should primarily occur through props.

How to Use Refs in React

In functional components, the useRef hook is the standard way to create and manage refs. For class components, createRef and callback refs are used.

Using useRef Hook (Functional Components)

The useRef hook returns a mutable ref object whose .current property is initialized to the passed argument (initialValue). The returned ref object will persist for the full lifetime of the component.

import React, { useRef, useEffect } from 'react';

function MyTextInput() {
  const inputRef = useRef(null); // Create a ref

  useEffect(() => {
    // Access the DOM element directly when the component mounts
    if (inputRef.current) {
      inputRef.current.focus(); // Focus the input
    }
  }, []); // Run once after initial render

  return (
    <div>
      <input type="text" ref={inputRef} /> {/* Attach the ref to the input element */}
      <button onClick={() => inputRef.current.blur()}>Blur Input</button>
    </div>
  );
}

export default MyTextInput;

In this example:

  1. useRef(null) creates a ref object inputRef.
  2. ref={inputRef} attaches this ref object to the <input> DOM element. React will set inputRef.current to the actual DOM node when the component renders.
  3. The useEffect hook then uses inputRef.current to call the focus() method directly on the DOM element.

Key Differences: Refs vs. State/Props

Understanding when to use refs versus state and props is crucial for building robust React applications.

Feature Refs State/Props
Purpose Direct imperative manipulation of DOM/instances Declarative UI updates, data flow, component re-renders
Triggers Render No (updates to .current do not trigger render) Yes (updates to state trigger re-renders)
Data Flow "Escape hatch" for non-React managed items Primary mechanism for data flow and UI management
Best Use Focus management, animations, third-party libs Dynamic content, user input, conditional rendering

For further reading on React refs and their usage, you can refer to the official React documentation on Refs and the DOM.