Frontend School
DashboardProblemsLearnPracticeMock InterviewReportsStatsBuy Credits
DashboardProblemsLearnPracticeMock Interview
React Interview Essentials
  1. 1.Introduction to React & Basic Setup
  2. 2.JSX, Functional Components & Props
  3. 3.State Management with useState & useEffect
  4. 4.Conditional Rendering & List Management
  5. 5.Event Handling & Form Management
  6. 6.React Router for SPA Navigation
  7. 7.Context API for Global State
  8. 8.Working with Refs & the DOM
  9. 9.Advanced Component Patterns: HOCs & Render Props
  10. 10.Building Reusable Logic with Custom Hooks
  11. 11.Performance Optimization with Memoization
  12. 12.Error Boundaries for Robust UIs
  13. 13.Concurrent React & Suspense
  14. 14.Testing React Components with RTL
  15. 15.Advanced State Management (Overview)
React Interview Essentials
08

React · Lesson 8 of 15 · 4 min

Working with Refs & the DOM

This is where interviewers test if you understand React's boundaries and its "escape hatches."

After this lesson, you'll know exactly when to break React's declarative model with refs, and how to explain the trade-offs in an interview. Refs are for imperative actions—when you need to tell an element how to do something, instead of just declaring what its state should be.

When to Reach for a Ref (and When Not To)

Use state for anything that React needs to know about to render the UI. Use refs for everything else you need to keep track of on a component instance.

The most common interview question on this topic is "When would you use a ref instead of state?" Your answer should be clear: state updates trigger re-renders, while mutating a ref does not. This makes refs suitable for two main categories of tasks.

First, for direct DOM manipulation. This is the "escape hatch."

  • Managing focus, text selection, or media playback (videoRef.current.play()).
  • Triggering imperative animations.
  • Integrating a third-party library that needs a raw DOM node (like a D3.js chart).

Second, for holding onto any mutable value that doesn't affect the render, like a timer ID or a previous state value. Storing setTimeout or setInterval IDs in a ref is a classic pattern to avoid bugs during cleanup.

The trap: Overusing refs. If you find yourself storing and reading from refs to decide what to render, you're fighting the framework. That's what state is for. Using a ref as a substitute for state is a red flag in an interview; it suggests you don't understand React's data flow.

The useRef Lifecycle

The useRef hook returns a plain JavaScript object with a single current property. This object persists for the entire lifetime of the component.

When you attach a ref to a DOM element in your JSX, like <input ref={myRef} />, React sets myRef.current to the corresponding DOM node after the component mounts. It's null before the initial render.

This is why you almost always access a DOM ref inside a useEffect hook or an event handler. By the time useEffect runs, the DOM has been updated and the ref's current property is set.

The trap: Accessing ref.current during the render phase. It will be null on the first render, and on subsequent renders it will hold the value from the previous render. Always access DOM refs in useEffect or event handlers to ensure you're working with the latest DOM.

Exposing DOM Nodes with forwardRef

By default, you can't pass a ref to your own functional component. React components don't automatically expose the DOM nodes they render. This is good encapsulation.

To bypass this, you wrap your component in React.forwardRef. This gives your component a second ref argument, which you can then "forward" to a specific DOM node inside it.

This is essential for creating reusable components like custom inputs, buttons, or video players that a parent component might need to control imperatively (e.g., to focus, click, or play).

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

// The child component receives the forwarded ref as a second argument.
const CustomInput = forwardRef<HTMLInputElement, { label: string }>(
  ({ label }, ref) => {
    return (
      <div>
        <label>{label}</label>
        {/* The ref is attached to the actual DOM element here. */}
        <input type="text" ref={ref} />
      </div>
    );
  }
);

// The parent component can now get a direct reference to the <input>
// inside CustomInput.
function ParentForm() {
  const inputRef = useRef<HTMLInputElement>(null);

  useEffect(() => {
    // Check for null, as the component might not be mounted.
    if (inputRef.current) {
      inputRef.current.focus();
    }
  }, []);

  return (
    <div>
      <h3>Focus Management with forwardRef</h3>
      <CustomInput label="Your Name:" ref={inputRef} />
    </div>
  );
}

In an interview, explain forwardRef as a tool for breaking a component's encapsulation in a controlled, explicit way. The parent doesn't get access to the child's state or internals, only to the specific DOM node that the child chooses to expose.

Customizing the Ref Handle with useImperativeHandle

This is a more advanced and less common hook. You use it with forwardRef to customize the value that gets exposed on the ref. Instead of exposing the entire DOM node, you can expose a custom object with specific methods.

For example, you could expose a handle with focus(), clear(), and shakeOnError() methods, but not the raw input node itself. This provides a cleaner, more limited API for the parent component, which is great for reusable component libraries.

Mentioning useImperativeHandle shows depth of knowledge, but don't overemphasize it. It's a specialized tool, not an everyday one.

Try it

Create a form with several input fields. Add a "Submit" button. If the user clicks "Submit" and one of the fields is empty, use a ref to automatically focus the first invalid input field. This is a realistic use case you'll encounter.

Next: We'll look at patterns for sharing logic and structure between components in "Advanced Component Patterns: HOCs & Render Props".

Lock it in — apply this lesson under interview conditions.

Try an AI mock interview
Previous

Context API for Global State

Next

Advanced Component Patterns: HOCs & Render Props