logoESLint React
Rules

no-unnecessary-use-ref

This rule is experimental and may change in the future or be removed. It is not recommended for use in production code at this time.

Full Name in @eslint-react/eslint-plugin

@eslint-react/no-unnecessary-use-ref

Full Name in eslint-plugin-react-x

react-x/no-unnecessary-use-ref

Features

๐Ÿงช

Presets

strict strict-typescript strict-type-checked

Description

Disallows unnecessary usage of useRef.

If a ref holds a value that is only used inside a single effect, it is unnecessary to use useRef. Instead, co-locate the value inside the effect that uses it.

Examples

Failing

import React, { useEffect, useRef } from "react";

function MyComponent() {
  const ref = useRef<number | null>(null);
  //    ๐ŸŸก Avoid: Unnecessary use of `useRef`. Instead, co-locate the value inside the effect that uses it.

  useEffect(() => {
    ref.current = requestAnimationFrame(() => {});
    return () => {
      if (ref.current != null) {
        cancelAnimationFrame(ref.current);
      }
    };
  }, []);
}

Passing

import React, { useEffect } from "react";

function MyComponent() {
  useEffect(() => {
    let ref: number | null = requestAnimationFrame(() => {});
    //  โœ… Good: Using a local variable to co-locate the value inside the effect that uses it.
    return () => {
      if (ref != null) {
        cancelAnimationFrame(ref);
      }
    };
  }, []);
}
import React, { useEffect, useRef } from "react";

function MyComponent() {
  // โœ… It's OK to use `useRef` here because the ref is used outside of the effect as well.
  const inputRef = useRef<HTMLInputElement | null>(null);
  useEffect(() => {
    if (inputRef.current != null) {
      inputRef.current.focus();
    }
  }, []);
  return <input ref={inputRef} />;
}
import React, { useRef } from "react";

function MyComponent() {
  // โœ… It's OK to use `useRef` here because the ref can be used for other purposes, and if not, the no-unused-vars rule will catch it.
  const ref = useRef<number | null>(null);

  // ...
}

Implementation


See Also

On this page