In React components, we can use the useRef
hook or createRef
function to create a ref.
A ref is a value that doesn’t trigger a re-render of the component when it’s changed as opposed to states and props.
In this article, we’ll look at the difference between the useRef
hook and the createRef
function in React components.
Difference Between useRef and createRef
The difference between the useRef
hook and the createRef
function is that the useRef
hook holds its value between re-renders in a function component.
The existing ref persists between re-renders.
createRef
is used to create a ref and a new ref is created during each render.
For instance, if we have:
import React, { createRef, useEffect, useState } from "react";
export default function App() {
const [count, setCount] = useState(0);
const ref = createRef();
useEffect(() => {
ref.current = "foo";
}, []);
useEffect(() => {
console.log(count, ref.current);
}, [count]);
return (
<div className="App">
<button onClick={() => setCount((c) => c + 1)}>increment</button>
<p>{count}</p>
</div>
);
}
We create a ref with createRef
.
And we only set ref.current
on initial render.
And to trigger a re-render, we update the count
state when we click on the button.
We can see from the console log in the useEffect
callback that ref.current
logs 'foo'
on the first render.
But then on subsequent renders, ref.current
is null
.
On the other hand, if we use the useRef
hook by writing:
import React, { useEffect, useRef, useState } from "react";
export default function App() {
const [count, setCount] = useState(0);
const ref = useRef();
useEffect(() => {
ref.current = "foo";
}, []);
useEffect(() => {
console.log(count, ref.current);
}, [count]);
return (
<div className="App">
<button onClick={() => setCount((c) => c + 1)}>increment</button>
<p>{count}</p>
</div>
);
}
We call the useRef
hook to create a ref.
And we set ref.current
as we did in the previous example.
The rest of the code is also the same.
The difference is that we see ref.current
is 'foo'
after each render.
This means in function components, we can use the useRef
hook to create a value that doesn’t trigger a re-render when it’s changed, but we can use it to keep values between re-renders.
Conclusion
The difference between createRef
and useRef
is that createRef
creates a new ref on every render in function components.
On the other hand, a ref created with useRef
keeps the same value after each render in a function component.