UseRef Hook In React Simply Explained

React

17/07/2021


The useRef hook returns nothing more than a JavaScript object with a current key. And just like any other object, we can assign a new value to that key as we please.

JAVASCRIPT
const refObject = useRef('initialValue')
useEffect(() => {
if (!refObject.current) return
console.log(refObject.current) // initialValue
refObject.current = 'newValue'
console.log(refObject.current) // newValue
})

No rerenders with updates

Whenever you assign a new value to current, your component is not rerendered. Compare this in contrast to useState where any updates will trigger a rerender of your React component.

The reason for this is that Refs exist outside of a component's rendering cycle. This allows you to store and persist data across renders. Consequently, Refs are suited for avoiding stale closures.

Accessing HTML elements

Another frequent use case of this hook is gaining access to the DOM. This is done by passing in the Ref to a React element, which consequently assigns the DOM node to the current key.

JSX
useEffect(() => {
if (!refObject.current) return
console.log(refObject.current) // <div>Some HTML element</div>
refObject.current.style.color = 'red'
})
return (
<div ref={refObject}>Some HTML element</div>
)

WRITTEN BY

Code and stuff