In my previous post, we talked about useMemo, when we should use it and why we shouldn't overuse it. In this post, we will be looking at the useRef hook and the common use-cases. Let get into it right away.
What is the useRef hook
According to the React documentation,
useRef returns a mutable ref object whose current property is initialized to the passed argument (initialValue). The returned object will persist for the full lifetime of the component.
In short, useRef is kinda similar to the useState hook, except it returns a mutable object and doesn't cause a component to re-render.
To use the value returned from useRef you need to call the current value. i.e
const ref = useRef('Dami')
console.log(ref.current);
// Dami
useRef use cases.
One of the common useCase for useRef is to use it as a reference to a dom element. Every JavaScript DOM element has a ref
attribute and you can use the useRef hook to get access to that element. eg.
import "./styles.css";
import React, { useRef, useState } from "react";
export default function App() {
const [name, setName] = useState();
const [message, setMessage] = useState();
const inputRef = useRef();
const lettersOnly = /^[A-Za-z]+$/;
const testLetters = () => {
if (name.match(lettersOnly)) {
setMessage("Success");
} else {
inputRef.current.focus();
setMessage("Please do not enter a number");
}
};
return (
<div className="App">
<input
ref={inputRef}
placeholder="Do not enter a number"
onChange={(e) => setName(e.target.value)}
/>
<button onClick={testLetters}>Check</button>
<div>
<small>{message}</small>
</div>
</div>
);
}
In the code above we're using the useRef hook to focus on the input field when a user enters a number into the box.
You'll notice that I am still using useState to hold the value of the content. You would actually want to do this, it is generally a good idea to let react handle your input value in a state instead of using javascript DOM, if not, why else are you using react anyways?
Another common use case for useRef is to know the number of times a component rerenders. Because the useRef hook actually doesn't cause the component to rerender, you can actually use it to target the number of rerenders.
import React, { useRef, useState, useEffect } from "react";
import "./styles.css";
export default function App() {
const [number, setNumber] = useState();
const rendered = useRef(0);
useEffect(() => {
rendered.current = rendered.current + 1;
});
return (
<div className="App">
<input value={number} onChange={(e) => setNumber(e.target.value)} />
<div>I rendered {rendered.current} times</div>
</div>
);
}
Conclusion
The useRef hook is one of those hooks that I rarely use but there's more to using useRef.
I hope this was able to add some clarification to the useRef hook. If you have any questions, comments, or suggestions please send them in the comment below. In my next post, we'll be looking into the useCallback
hook. Meanwhile, stay safe and keep doing amazing things.