Hackernoon logoReact useRef Hook Explained with Examples by@kliukovkin

React useRef Hook Explained with Examples

Georgii Kliukovkin Hacker Noon profile picture

@kliukovkinGeorgii Kliukovkin


Well, we all know that ref helps us to get access to the DOM. But let's consider the next situation, we have some React component and we want to know how many times this component was rendered. How can we achieve that? Well, maybe we can use React

hooks to determine that the component was re-rendered. Something like this:

As you can see it doesn't work as we want. After the component was rendered we set a new state which follows component re-rendering and setting state again. Infinity loop.

Maybe we could just create an object and update the value each time the component re-rendered?

No, doesn't work. Every render create its own scope and each scope has its own

. So, maybe we can just take this state away from the component, right?

It works, but it is not good practice to keep anything outside the component. And here is a time when

hook will help us. As written in the documentation, useRef returns a mutable ref object whose .current property is initialized to the passed argument (initialValue)."

Every render shares the same mutable object created by the useRef hook. It is a perfect way to share the state between each render without causing a new render.


Join Hacker Noon

Create your free account to unlock your custom reading experience.