Open In App

How is useRef different from using 'ref' with class components?

Last Updated : 24 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

In class components, ref is a special attribute used to reference DOM elements or React components. You create a ref in the constructor, attach it to the element, and then manipulate it using the ref object. ReactJS useRef is a hook in functional components for referencing DOM elements or other values. It returns a mutable object that you attach to the element, allowing you to access and modify it directly.

Syntax:

  • With class components, you use the ref attribute directly within JSX elements
<input ref={this.myRef} />
  • With functional components, you use the useRef hook.
const myRef = useRef();

Ref Management in Class and Functional Components:

  • Accessing the Ref Object:
    • In class components, you access the ref object using this.myRef.
    • In functional components, you access the ref object directly as myRef.current.
  • Managing Lifecycle:
    • In class components, you can access the lifecycle methods like componentDidMount, componentDidUpdate, etc., to manipulate the ref.
    • In functional components, you don't have access to lifecycle methods directly. Instead, you might use useEffect hook to perform actions after render.
  • Usage with DOM Elements:
    • Both useRef and ref can be used to reference DOM elements. However, with useRef, you access the DOM element via current property, while with ref in class components, you directly access the DOM element via the ref object.

Example 1: Below is the example of ref in React using class component.

JavaScript
import React,
{
    Component
} from 'react';

class FocusInputClass extends Component {
    constructor(props) {
        super(props);
        this.textInput = React.createRef();
    }

    focusInput = () => {
        this.textInput.current.focus();
    };

    render() {
        return (
            <div>
                <input type="text"
                    ref={this.textInput} />
                <button onClick={this.focusInput}>
                    Focus Input
                </button>
            </div>
        );
    }
}

export default FocusInputClass;

Output:

gfg28
Output

Example 2: Below is the example of useRef in React using functional component.

JavaScript
import React,
{
    useRef
} from 'react';

const FocusInputFunctional = () => {
    const textInput = useRef(null);

    const focusInput = () => {
        textInput.current.focus();
    };

    return (
        <div>
            <input type="text"
                ref={textInput} />
            <button onClick={focusInput}>
                Focus Input
            </button>
        </div>
    );
};

export default FocusInputFunctional;

Output:

gfg28
Output

Next Article

Similar Reads