The useRef Hook allows you to persist values between renders. It can be used to store a mutable value that does not cause a re-render when updated. It can be used to access a DOM element directly.
Does Not Cause Re-renders
If we tried to count how many times our application renders using the
useState Hook, we would be caught in an infinite loop since this Hook itself causes a re-render.
To avoid this, we can use the
useRef() only returns one item. It returns an Object called
When we initialize
useRef we set the initial value:
Run this on your computer and try typing in the input to see the application render count increase.
Accessing DOM Elements
In general, we want to let React handle all DOM manipulation.
But there are some instances where
useRef can be used without causing issues.
In React, we can add a
ref attribute to an element to access it directly in the DOM.
Tracking State Changes
useRef Hook can also be used to keep track of previous state values.
This is because we are able to persist
useRef values between renders.