React useRef Hook Explained with Examples by@kliukovkin

React useRef Hook Explained with Examples

React's useRef hook is a perfect way to share the state between each render without causing a new render. It is not good practice to keep anything outside the component. Every render create its own scope and each scope has its own state. UseRef returns a mutable ref object whose current property is set to be updated each time the component re-rendering is re-rendered. The state is set after the component was rendered and set a new state after each render is rendered. It works, but it is not a good idea to keep state outside of component.
image
Georgii Kliukovkin Hacker Noon profile picture

Georgii Kliukovkin

Developer.

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

useEffect
and
useState
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

renderedCounter
. 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

useRef
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.

Tags

Join Hacker Noon

Create your free account to unlock your custom reading experience.