Try @eslint-react/kit@beta
logoESLint React

no-create-ref

Disallows 'createRef' in function components.

Full Name in eslint-plugin-react-x

react-x/no-create-ref

Full Name in @eslint-react/eslint-plugin

@eslint-react/no-create-ref

Presets

x recommended recommended-typescript recommended-type-checked strict strict-typescript strict-type-checked

Rule Details

createRef() is a legacy API that is not recommended for use in new code. Instead, prefer using useRef() with function components.

Examples

Using createRef in function components

In function components, prefer the Hook useRef over createRef, which was designed for class components.

import React, { createRef } from "react";

// Problem: Using createRef in a function component
function MyComponent() {
  const ref = React.createRef<HTMLDivElement>();
  //          ^^^ [Deprecated] Use 'useRef' instead.

  return <div ref={ref} />;
}
import React, { useRef } from "react";

// Recommended: Use useRef in function components
function MyComponent() {
  const ref = useRef<HTMLDivElement>(null);

  return <div ref={ref} />;
}

Using createRef in class components

createRef can still be used in class components, which is the intended use of this API.

import React, { createRef } from "react";

// OK: Using createRef in a class component is the intended use
class MyComponent extends React.Component {
  inputRef = createRef();
  // ...
}

Migrating from createRef to useRef

When migrating a class component to a function component, replace createRef with useRef.

// Problem: createRef inside a function component creates a new ref on every render
import { createRef } from "react";

function Form() {
  const inputRef = createRef(); // Does not persist across renders

  function handleClick() {
    inputRef.current.focus();
  }

  return (
    <>
      <input ref={inputRef} />
      <button onClick={handleClick}>Focus the input</button>
    </>
  );
}
// Recommended: useRef persists the same ref object across renders
import { useRef } from "react";

function Form() {
  const inputRef = useRef(null);

  function handleClick() {
    inputRef.current.focus();
  }

  return (
    <>
      <input ref={inputRef} />
      <button onClick={handleClick}>Focus the input</button>
    </>
  );
}

Versions

Resources

Further Reading


See Also

On this page