useRef Hook in React

Last Updated on June 17, 2024

useRef createRef
It is a hook. It is a function.
It uses the same ref throughout. It creates a new ref every time.
It saves its value between re-renders in a functional component. It creates a new ref for every re-render.
It persists the existing ref between re-renders. It does not persist the existing ref between re-renders.
It returns a mutable ref object. It also returns a mutable ref object.
The refs created using the useRef can persist for the entire component lifetime. The refs created using the createRef can be referenced throughout the component.
It is used in functional components. It is used in class components. It can also be used in functional components but might show inconsistencies.
function FancyInput(props, ref) {
  const inputRef = useRef();
  useImperativeHandle(ref, () => ({
    focus: () => {
      inputRef.current.focus();
    }
  }));
  return <input ref={inputRef} ... />;
}
FancyInput = forwardRef(FancyInput);

References
https://reactjs.org/docs/hooks-reference.html#useref
https://www.geeksforgeeks.org/difference-between-useref-and-createref-in-reactjs/
https://stackoverflow.com/questions/54620698/whats-the-difference-between-useref-and-createref