Capítulo 82 de 116

Chapter 82: createRef

Core Idea

createRef() creates a standalone ref object outside of the Hooks system — the class-component-era equivalent of useRef, appropriate only inside a class component's constructor, not in function components.

Key Concepts

  • Signature: const ref = createRef() — returns { current: null }, structurally identical to what useRef(null) returns.
  • Class-only usage pattern: called once in a class component's constructor and stored on this (this.inputRef = createRef()), then passed to a JSX element's ref attribute inside render().
  • Never call it in a function component. Unlike useRef, createRef() creates a brand-new ref object every time it's called — calling it directly in a function component's body would produce a fresh, disconnected ref on every render, defeating the entire point of a persistent ref. useRef exists precisely to solve this for function components.
  • Legacy status: this exists for maintaining class-component codebases; new code (function components) should always use useRef (Ch 62) instead.

Key Takeaways

  1. createRef belongs exclusively to class components — in function components, always use useRef.
  2. Calling createRef() inside a function component's render body is a bug: it produces a new, useless ref every render instead of a persistent one.
  3. Functionally, both APIs return the same { current: value } shape — the difference is entirely about when and how many times the ref object gets created.

Connects To

  • Ch 62 (useRef): the function-component equivalent, and the one to use in all new code.
  • Ch 79 (Component): the class-component base this API is meant to be used within.