React-useRef, What-Why-How?

Murat Güney
2 min readMay 29, 2021

With React 16.8 we have met with hooks and some methods that we have used before were replaced with them. One of those is “useRef”. There are 3 ways that are commonly used.

1 - What?

“useRef” is a hook which:

1 — can keep the values between re-renders. It has a “current” property that holds a mutable object.

2 — provides access to the corresponding DOM node which passed the return value of “useRef”.

3 — provides access to methods of child components with “useImperativeHandle”.

2 - Why?

1 — When the value of “useRef” is changed, it doesn’t trigger a re-render. So if you need to use a variable that doesn’t need to trigger a re-render when it changed, you should use “useRef” instead of “useState”. It holds the value that you passed between re-renders, how awesome it is, right? Replacing unnecessary “useState”s with “useRef”s will increase the performance of your components.

2 — It might be used to access a DOM node and its properties like “getBoundingClientRect”, “style” and all others. To update the style of an element, you may have used “useState”. As you know this works with re-renders. If you need to update the style of an element rapidly, like “Drag&Drop” or “Smooth Scroll”, replacing “useState” logic with “useRef” will increase the performance of your components.

3 — React works with passing properties to child components, and it is really easy to call a function that is passed from a parent component, in the child component. But if you want to access a method of child component, this may be harder. With “useImperativeHandle” you can do that easily.

3 - How?

1 — Enable/Disable toggle with “useRef”

2 — Drag element with “useRef”

3 — Access to child component’s methods