Skip to content
Tutorials Center
My learning

Topics

React Reference ยท Top-Level React APIs

React createRef() function

Reference for React createRef: create a ref object with a current property for class components, and why function components should use useRef instead.

createRef creates a ref object: a plain object { current: null }. You attach it to an element with the ref attribute, and after the component mounts React sets current to the DOM node (or to a class component's instance). It is the ref API for class components.

In function components use useRef instead. useRef returns the same object on every render, while createRef makes a brand-new object each time it is called, so any value you store in it is lost on the next render.

JSX
import { createRef } from 'react';

const inputRef = createRef();

Try it

A class component with createRef
createRef vs useRef in a function component

After two more clicks the first count keeps growing (one new object per render) while the second stays at 1.

Syntax

TypeScript
function createRef<T>(): { current: T | null };

It takes no arguments, and always starts with current equal to null.

Value of current When
null Before the first commit, and after the element is removed.
DOM node After mount, when attached to a DOM element such as <input>.
Component instance After mount, when attached to a class component.

Returns: a new plain object with a single current property. In React 19 development builds the object is sealed, so you cannot add other properties.

Usage notes

  • Create it once per instance in a class, as a class field (inputRef = createRef()) or in the constructor. Do not create it inside render, or the ref changes on every render and current is reset.
  • current is not available during the first render. Read it in event handlers, componentDidMount or effects, after React has attached it.
  • Refs are an escape hatch. Use them for focus, scrolling, measuring and calling imperative APIs, not to read or write data that belongs in state.
  • Function components: useRef is the right tool. createRef there recreates the object on every render. Reaching for createRef in a function component is a common mistake.
  • Ref on a function component: in React 19 it arrives as the ref prop (see ref as a prop); before React 19 you need forwardRef.
  • Do not store arbitrary values here in function components. Class components can store values in instance fields instead.
  • Alternative: a callback ref (ref={(node) => ...}) is useful when you must run code when the node attaches or detaches.