Course contentsShow
← React
Lesson 722 of 2,39619. useRefFree lesson

When to Use Refs vs State for DOM Interaction

Choosing between refs for imperative DOM access and state for declarative UI updates.

When to Use Refs vs State for DOM Interaction

You'll learn: How to decide whether a ref or state is the right tool when working with DOM elements in React.

Now that you understand both refs and state, you face a choice: when manipulating the DOM, which should you reach for? The answer hinges on whether you're updating the UI or performing an imperative action.

The Decision Framework

Use state when:

  • The DOM change reflects a UI state that React should manage
  • You want React to re-render and keep everything in sync
  • The change affects what the user sees (visibility, content, styling)

Use refs when:

  • You need imperative control without triggering re-renders
  • You're calling browser APIs (focus, scroll, play/pause)
  • The action is a side effect, not a state change
  • Performance matters and re-rendering would be wasteful

The Analogy

Think of state as a control panel that updates the entire dashboard when you flip a switch. Think of refs as a direct phone line to a specific piece of machinery—you give it a command without alerting the whole system.

Examples in Context

State: Showing/hiding a modal, toggling dark mode, displaying form errors—these change what React renders.

Refs: Focusing an input after submission, scrolling to an element, starting video playback, measuring an element's dimensions—these are one-time commands to the browser.

The Test

Ask yourself: "Does this change need to trigger a re-render?" If yes, use state. If no, use a ref.

Key Takeaway: Use state for declarative UI changes that React should track and re-render; use refs for imperative DOM commands that don't require re-rendering.