DEV Community 👩‍💻👨‍💻

Discussion on: Using refs in React.js

Collapse
 
lukeshiru profile image
Luke Shiru

The idea with element refs is to use them mainly when interfacing with external libraries that don't interact with React directly. So, for example, using it to get the current value of an input or to focus an input are both bad usages of ref. To get the current value, you can just turn your input into a controlled element, and to focus you can just use autoFocus. So instead of doing this:

const inputRef = useRef();

useEffect(() => inputRef.current?.focus());

return (
    <form onSubmit={() => send(inputRef.value)}>
        <input ref={inputRef} />
    </form>
);
Enter fullscreen mode Exit fullscreen mode

Yo do this:

const [value, setValue] = useRef();

return (
    <form onSubmit={() => send(value)}>
        <input
            autoFocus
            value={value}
            onChange={({ currentTarget: { value } }) => setValue(value)}
        />
    </form>
);
Enter fullscreen mode Exit fullscreen mode

The short version is: Don't use refs for DOM interactions with elements you control, and instead just use them when you want to interact with external libraries, or when you want to store a value without triggering re-renders.

Cheers!

Collapse
 
amoled27 profile image
Amod Shinde Author

Thanks, totally agree with you. I just gave a sort of demo on how refs work. In simple words:
There are controlled and uncontrolled components in React. Libraries or external files which we may use in React come under uncontrolled components.
As the name says, we dont have a control over it via React app, hence we cant use traditional document.getElement queries to manipulate DOM.
Thus, react refs come into the picture to access and manipulate these uncontrolled components.