javascriptreactjs

Difference between useRef vs document.getElementById to focus an input


I'm following a React tutorial and currently have this React code:

import { useRef } from 'react';

const AddItem = ({ newItem, setNewItem, handleSubmit }) => {
    const inputRef = useRef();

    return (
        <form className="addForm" onSubmit={handleSubmit}>
            <input
                ref={inputRef}
                id="addItem"
                type="text"
                value={newItem}
                onChange={(e) => setNewItem(e.target.value)}
            />
            <button
                type="submit"
                onClick={() => inputRef.current.focus()}
                // onClick={() => document.getElementById('addItem').focus()} // What does this do differently?
            >
            </button>
        </form>
    );
};

export default AddItem;

I'm using useRef() along with onClick={() => inputRef.current.focus()} to make sure the text input is focused after clicking the button.

I can do the same thing without the need for the useRef hook by using onClick={() => document.getElementById('addItem').focus()}.

Is there a benefit to using the useRef method over the getElementById method?


Solution

  • In React you don't usually access the DOM directly, you let React do that for you. Using React refs is a way to do it. You do not need to assign ids this way or use other query selectors.

    This answer goes into details: https://stackoverflow.com/a/69260293/13637489

    A lot of informations can be found directly in the React documentation: