ref prop should not be used on React function components

  • REACT_FUNC_COMPONENT_INVALID_REF_PROP
  • Error
  • Medium
  • react

This rule applies when a ref prop is specified on a React function component.

The ref prop is used to provide a reference to the component instance of the current element. However, because a function component does not have any instances, it cannot be used on an element corresponding to a function component.

If the intention is to refer an inner element of the function component, you can use React.forwardRef() instead.

Note: The application of this rule is limited to projects using React 18 or below because React 19 supports using ref for function components.

Noncompliant Code Example

View with compliant examples side by side
import { useRef } from 'react';

function MyInput(props) {
  return <input />;
}

export function App() {
  const myInput = useRef(null);
  return (
    <>
      <MyInput ref={myInput} /> {/* REACT_FUNC_COMPONENT_INVALID_REF_PROP alarm */}
      <button onClick={() => myInput.current.focus() }>
        Edit
      </button>
    </>
  );
}

Compliant Code Example

View with noncompliant examples side by side
import { forwardRef, useRef } from 'react';

const MyInput = forwardRef((props, ref) => {
  return <input ref={ref} />;
});

export function App() {
  const myInput = useRef(null);
  return (
    <>
      <MyInput ref={myInput} />
      <button onClick={() => myInput.current.focus() }>
        Edit
      </button>
    </>
  );
}

Version

This rule was introduced in DeepScan 1.27.0.

See

  • Refs and Function Components

  • React Warning: Function components cannot be given refs. Attempts to access this ref will fail. Did you mean to use React.forwardRef()?

Was this documentation helpful?