React useRef in 3 minutes

Yosua Halim
2 min readMay 13, 2022

Okay, today we will learn how to use useRef hook in our projects and how useful this hook. In this article I am going to tell you everything you need to know about refs, let’s begin.

Below I have code sandbox you can play with so you can follow.

In the sandbox, I have a simple code that can render every time you type in the input tag. This is a very basic how react application works.

export default function App() {const [name, setName] = useState("");return (<div className="App"><input value={name} onChange={(e) => setName(e.target.value)} /><div>My name is {name}</div></div>);}

The biggest use case that people use useRef that you can reference elements inside your HTML and this is so popular. That each elements in your document has a ref attribute, you can name it whatever you want.

const inputRef = useRef();<input ref={inputRef} value={name} onChange={(e) => setName(e.target.value)} />
<button onClick={focus}>Focus</button>

So, now let me add button tag on the code to show you guys how useRef works. The goals is when you click the button it will focus on the input tag using ref.

Now we can create onClick function on the button to see how it works.

function focus() {console.log(inputRef);inputRef.current.focus();}

When we console log the inputRef we can see that inputRef is an object that have current key and the value is the input tag. This is exactly the same when we using document query selector to get the input tag and have exact same DOM node.

Because this is so easy, people tend to abuse this power instead of letting react manage all of your state and all of your values on onChanges and this is make the render problem because the state is not change and not causing re-render. This is something you never want to do. in React you always want to do your management through React State and Props instead change using refs.

Store Previous State

Another use case useRef can do is you can store previous value of your state for example we can add useEffect hooks to store the the name every time the name state change.

useEffect(()=>{previousRef.current = name}[name])

As you can see on the sandbox, the previousRef store the previous state before it changes.

Conclusion

Refs in React are incredibly useful for accessing and manipulating DOM elements directly. Refs are also amazing at persisting data between renders, which is makes it possible to store persisted component data without causing a re-render when it is changed.

--

--

Yosua Halim

Software Engineer, love all about technologies and love to learn.