Skip to main content

Overview

Refs provide a way to access DOM nodes or React elements created in the render method. They’re useful for managing focus, text selection, media playback, triggering animations, and integrating with third-party DOM libraries.

Creating Refs

Using useRef Hook

The useRef hook is the modern way to create refs in function components:

API Signature

From packages/react/src/ReactHooks.js:82:
The hook returns a mutable ref object whose .current property is initialized to the passed argument.

Using createRef (Class Components)

From packages/react/src/ReactCreateRef.js:

Forwarding Refs

ForwardRef allows components to pass refs through to their children. This is useful when building reusable component libraries.

API Signature

From packages/react/src/ReactForwardRef.js:12:

Basic Example

From packages/react/src/ReactForwardRef.js:31, the render function must accept exactly two parameters:
Always use the signature (props, ref) => { ... }.

Advanced ForwardRef with useImperativeHandle

Customize the instance value that is exposed to parent components:

Callback Refs

Callback refs give you more control over when refs are set and unset:

Practical Use Cases

Managing Focus

Text Selection

Scroll Management

Third-Party Library Integration

Refs with Mutable Values

Refs can store any mutable value, not just DOM nodes:

Storing Previous Values

ForwardRef Implementation Details

From packages/react/src/ReactForwardRef.js:51:
From packages/react/src/ReactForwardRef.js:19, never wrap a memoized component with forwardRef:
Correct order: memo(forwardRef(Component))

Best Practices

  1. Avoid overusing refs: Use props and state for data flow when possible
  2. Don’t access refs during render: Refs are for side effects, not rendering logic
  3. Use callback refs for dynamic elements: When the ref target may change
  4. Clean up side effects: Always clean up intervals, listeners, etc. in useEffect cleanup
  5. Type your refs: Use TypeScript or JSDoc to specify ref types
  6. Combine with useImperativeHandle: Expose only necessary methods to parent components

When to Use Refs

Refs are ideal for:
  • Managing focus, text selection, or media playback
  • Triggering imperative animations
  • Integrating with third-party DOM libraries
  • Storing mutable values that don’t trigger re-renders
Refs should not be used for:
  • Anything that can be done declaratively
  • Accessing child component state (use state lifting instead)
  • Replacing props or state

See Also

  • Hooks - Learn about useRef and useImperativeHandle
  • Component API - Component APIs and lifecycle