CodeBlanks Logo Icon CodeBlanks

DOM access

Learn to reach a DOM node through a ref.

DOM access

The most common use of useRef is direct DOM access. You create a ref with const inputRef = useRef(null);, then bind it to an element with <input ref={ '{ inputRef }' } />.

Once bound, inputRef.current points to the real DOM element. So you can programmatically focus with inputRef.current.focus(), read the value with inputRef.current.value.

React usually discourages direct DOM access, but it's unavoidable in some cases: autofocus, measuring (getBoundingClientRect), canvas or video control, third-party library integration.

Initial value null

For DOM binding, the ref's initial value is usually null: useRef(null). This is so current doesn't point to any element before binding.

On the first render, React binds the ref and current points to the real DOM element. When the component unmounts, React sets it back to null.

So inputRef.current.focus() goes inside a useEffect or an event handler; you don't call it directly during the first render.

Practice Auto focus

Complete the skeleton. Write a SearchBox component. Create inputRef = useRef(null). Inside useEffect, call inputRef.current.focus(). Show <input ref={ '{ inputRef }' } placeholder="Search" />. Export it.

Starter code

App.jsx
import { useRef, useEffect } from "react";

// Write the SearchBox component here

Sample solution

App.jsx
import { useRef, useEffect } from "react";

function SearchBox() {
  const inputRef = useRef(null);
  useEffect(() => {
    inputRef.current.focus();
  }, []);
  return <input ref={inputRef} placeholder="Search" />;
}

export default SearchBox;

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 DOM binding

Question
To bind a ref to a DOM element, use the ____ prop.
Answer
To bind a ref to a DOM element, use the ref prop.

Explanation: Binding is via the ref prop.

2 Which operation needs useRef?

  • Sorting an array
  • Changing CSS
  • Putting a value in state
  • Programmatic focus on an input Correct answer

Explanation: useRef is used for programmatic focus.

3 Match the DOM ref steps

Term Meaning
useRef(null) Initial value
ref={inputRef} Binding
current.focus() Focus
useEffect Side effect

All lessons in Beginner