When should you use the useRef hook?
As you might know, using the useState
hook causes the component to re-render.
Usually, we want the component to re-render! However, there are times in which we only want to change the variable but not re-render the component.
For example, I have created a custom hook to use inside an infinite scroll component.
const useInfinite = () => {const [items, setItems] = useState([]);const [loading, setLoading] = useState(false);const page = useRef(1);const count = useRef();// ....}
The API that I am using accepts parameters such as page and limit and returns the total count and the items filtered according to parameters.
When I use this hook, I want to re-render my component when the current items are updated or loading state changes. As a result, I store them inside an useState
hook.
However, I don't want to re-render my component when I update the page number or the total item count. As a result, I use useRef
for them as they do not need to trigger re-rendering.
There are more reasons to use the useRef
hook; however, simply knowing which variables are associated with a re-rendering is crucial in deciding whether you should use useState
or useRef
.