Back to results for “Refs”
React › Refs, useRef & forwardRef

What is the difference between a ref created with useRef and one created with createRef?

Beginner

Answer

useRef is meant for function components and keeps the same ref object across every render, which is almost always what you want. createRef is the older approach used inside class components, and it creates a brand new ref object every single render if called incorrectly, so it should not normally be used inside function components.
// Correct, function component, useRef keeps the same ref across renders
function MyComponent() {
  const myRef = useRef(null);
}

// Correct usage, class component, createRef called once in the constructor
class MyClassComponent extends React.Component {
  constructor(props) {
    super(props);
    this.myRef = React.createRef();
  }
}
Real-world example A team maintaining an older class based component correctly uses createRef inside the constructor, while all their newer function components consistently use useRef instead.

Common follow-ups: What mistake happens if createRef is accidentally called during every render instead of just once?;Is there ever a good reason to use createRef inside a modern function component?