useRef Hook helps to create a direct reference to the DOM element,
so we can access it and modify, like the JavaScript document.querySelector
method.
const refContainer = useRef(initialValue);
It returns an object which has a property called .current
.
So writing useRef(0)
is similar to {current : 0}
The object persists the value for the full lifecycle of the component. Moreover it does not cause re-renders when we change the value, like useState and othe Hooks does.
Lets see some code examples:
import { useRef, useEffect } from "react";
const App = () => {
const refElement = useRef();
useEffect(() => {
console.log("render"); // to check whether it re-renders
})
const buttonHandler = () => {
refElement.current.focus();
refElement.current.value = "Hello";
};
return (
<>
<input ref={refElement} />
<button onClick={buttonHandler}>Click Me</button>
</>
);
};
export default App;
If you look at the code above, we initialised useRef Hook to a variable named refElement
.
We added useEffect Hook just to check whether the component re-renders or not.
Then we have a function buttonHandler
.
Now in the DOM, we have an input field which references to the refElement
,
and a button with an onClick
method which triggers the buttonHandler
function.
When this component is rendered, the useEffect Hook will run and display the console value on the first render. We have not passed any dependency array to useEffect Hook, so it is supposed to run on every re-render of the component. But as we know, useRef will not cause a re-render- let's see it in action.
When we click on the button, buttonHandler
function is called, refElement.current.focus()
runs which just gives a focus to the input box.
Then we change the ref value by refElement.current.value = "Hello"
The value of refElement
is changed to Hello, which now is displayed in the input field, as we has given a reference to refElement
.
But we dont see anything in the console
because the useEffect Hook hasn't run, which means there was no re-render!
Well, then can you replace Hooks like useState, which causes a re-render when its value is changed, with useRef?
As useRef doesn't cause a re-render, React can't display any other child components or elements that depends on the value of useRef.
Let's connect on twitter . Happy coding!