Welcome back again!
This is the fourth blog in the React Hook series, where we're learning about different hooks used in React, and our today's hook is the useRef
hook. Before we get started, I'd recommend reading the last blogs of this series React Hooks. Though this hook is completely independent of we can read and learn it without any prior knowledge of hooks, it would be beneficial to have some basic understanding of the hooks.
What is useRef Hook
We can build a direct reference to a DOM element using the useRef
hooks. It's used to keep track of mutable values that do not cause re-rendering every time they're changed.
Syntax:
const refContainer = useRef(intialValue)
Example:
const countRef = useRef(0)
useRef
returns a mutable object whose current
property can be used to access the value.
In the above syntax, we have initialized the useRef
with the initial value of 0.
const countRef = {counter:0} is same as const count = useRef(0)
Difference between useState and useRef
We can see in the following codesandbox that using the useRef
we can persist the previous value on every render. But using the same with useState
is not possible.
Advantage of using useRef
- It allows us to directly access the DOM element without causing any issue.
- Values updated using
useRef
do not cause re-rendering.
Ending
That's all for this blog. Continue reading this React hook series to learn more about React hooks. In the next blog, we'll look at the 'useReducer' hook, which is used to handle state management in React globally. Feel free to leave your valuable feedback in the comments below.
To learn more about React, JavaScript, and Web development, follow me on Twitter.
Reference: W3Schools