React Refs and the DOM: A Practical Guide to Direct DOM Manipulation in React

Last updated 2 months, 2 weeks ago | 138 views 75     5

Tags:- React

Introduction: Why React Refs Matter

React encourages a declarative approach to building UIs, but sometimes you just need to manipulate the DOM directly—like setting focus on an input field, scrolling to a section, or triggering animations.

That’s where React Refs come in.

Refs (short for “references”) let you access DOM nodes or React elements directly without relying on state or props. While you should use them sparingly, they’re perfect when you:

  • Need to focus an input on mount

  • Control uncontrolled form elements

  • Integrate with third-party DOM libraries (like animations or sliders)

Let’s break down how Refs work and how you can use them effectively in your React apps.


What Are React Refs?

A ref is an object created by React.createRef() or useRef() that gives you access to a DOM node or component instance.

  • In class components, use React.createRef()

  • In functional components, use useRef()


Creating Refs in React

1. Using useRef in Functional Components

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

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

  useEffect(() => {
    inputRef.current.focus(); // Focus the input after component mounts
  }, []);

  return <input ref={inputRef} placeholder="Auto-focused input" />;
}
  • inputRef.current holds the actual DOM node.

  • useRef() persists across re-renders but doesn't trigger a re-render when updated.


2. Using createRef in Class Components

import React, { Component } from 'react';

class MyComponent extends Component {
  constructor(props) {
    super(props);
    this.inputRef = React.createRef(); // Create a ref
  }

  componentDidMount() {
    this.inputRef.current.focus(); // Access the DOM node
  }

  render() {
    return <input ref={this.inputRef} placeholder="Focus me!" />;
  }
}
  • createRef() is re-initialized every render, so it’s best suited for class components.


Common Use Cases for Refs

Use Case Description
Focus input field Automatically focus on mount or event
Scroll to an element element.scrollIntoView() on ref
Trigger animations Integrate with libraries like GSAP or anime.js
Access child methods Call methods on class components (rare, avoid in favor of composition)
Manage media elements Control audio/video via ref (e.g., .play(), .pause())

Full Example: Scroll to a Section on Button Click

import React, { useRef } from 'react';

function ScrollDemo() {
  const sectionRef = useRef(null); // Ref for the section

  const scrollToSection = () => {
    sectionRef.current.scrollIntoView({ behavior: 'smooth' }); // Smooth scroll
  };

  return (
    <div>
      <button onClick={scrollToSection}>Go to Section</button>

      <div style={{ height: '100vh' }}></div> {/* Spacer */}
      
      <div
        ref={sectionRef}
        style={{ height: '100px', backgroundColor: 'lightblue' }}
      >
        Target Section
      </div>
    </div>
  );
}

✅ This shows how Refs can be used for navigation and dynamic interaction.


Tips & Common Pitfalls

Tips

  • Use Refs only when necessary. Try declarative solutions first.

  • Prefer useRef for mutable values that don’t trigger re-renders.

  • Combine with useEffect for timing interactions (like focusing inputs).

Common Pitfalls

  • Don’t use Refs to sync state or manage data flow—that's what props and state are for.

  • Avoid using Refs for conditional rendering logic—React won’t re-render based on .current.

  • Don’t overuse Refs to bypass React’s rendering logic—you'll make code harder to maintain.


Comparison Table: useRef vs createRef

Feature useRef createRef
Used in Functional components Class components
Persistence Persists between renders Recreated on every render
Triggers re-render ❌ No ❌ No
Best used for DOM access, mutable values DOM access in class components

Conclusion: When to Use React Refs

React Refs are powerful tools that give you low-level access to DOM elements when needed. While React encourages a declarative style, Refs give you the control and flexibility for certain use cases.

Use them wisely, and they’ll make your components more dynamic and interactive—especially for forms, media, and scroll behavior.


Key Takeaways

  • Use useRef() in functional components and createRef() in class components.

  • Access DOM nodes directly via ref.current.

  • Avoid using Refs for state-like logic or component data flow.

  • Best suited for interactions like focus, scroll, animation, and media control.