Introduction To React Ref
I am a Frontend Engineer from Nigeria. I love to solve problems one line of code at a time.
REACT USEREF HOOK: REFS
React refs are strongly associated with the DOM. This has been true in the past, but not anymore since React introduced React Hooks. Ref means just reference, so it can be a reference to anything (DOM node, JavaScript value, ...). Let's take the following React component as example:
import * as React from 'react';
export default function Counter() {
const [count, setCount] = React.useState(0);
function onClick() {
setCount(prevCount => prevCount + 1);
}
return (
<div>
<p>{count}</p>
<button type="button" onClick={onClick}>
Increase
</button>
</div>
);
}
React offers us the React useRef Hook which is the status quo API when using refs in React function components. The useRef Hook returns a mutable object which stays intact over the lifetime of a React component. Specifically, the returned object has a current property which can hold any modifiable value for us:
import * as React from 'react';
export default function Counter() {
/* Here */
const hasClickedButton = React.useRef(false);
const [count, setCount] = React.useState(0);
function onClick() {
setCount(prevCount => prevCount + 1);
/* Here */
hasClickedButton.current = true;
}
/* Here */
console.log('Has clicked button? ' + hasClickedButton.current);
return (
<div>
<p>{count}</p>
<button type="button" onClick={onClick}>
Increase
</button>
</div>
);
}
The ref's current property gets initialized with the argument we provide for the useRef hook (here false). Whenever we want, we can reassign the ref's current property to a new value. In the previous example, we are just tracking whether the button has been clicked.
The thing about setting the React ref to a new value is that it doesn't trigger a re-render for the component.
Reference: https://www.robinwieruch.de/react-ref/