React hooks are very useful functions provided in React functional component and one of them is useRef hook. We have also covered other hooks like useEffect, useContext, useMemo.
What is useRef Hook
Sometime, we need to hold a reference to an element or a component that render in a react component. We can use useRef hook in this context. useRef hook creates a reference pointer to a DOM to allow us to manipulate the element in the situation when logic requires.
Usually, we will use a change in a state variable to trigger other hooks or to change a state of the UI element. However, there may be some time when we want to trigger a change without having a state. Hence, useRef hook can be useful in such a situation.
Note that since this is a hook, we will not be able to use this hook to point to dynamically generated element.
Official useRef documentation.
Using useRef Hook
In the below example, instead of having a state to update input value on every change, we change the logic a little to illustrate how to use useRef.
First, we use ‘elementRef’ variable to hold onto the input object so that we can access its DOM properties or even manipulate it. Then, we input some numbers and click on the button to trigger a calling function. The function can then access the input value with ‘elementRef.current.value’.
One of the advantage is that value is only read and updated on button click. No function is executed when the text is entered into the input.
import React, { Fragment, useState, useRef } from 'react';
const app = () => {
const [appleCount, setAppleCount] = useState(100);
const elementRef = useRef(null);
const updateCount = () => {
setAppleCount(elementRef.current.value);
elementRef.current.focus();
};
return (
<Fragment>
Current apple count : {appleCount}
<input type='text' ref={elementRef} />
<button onClick={updateCount}>Update from input</button>
</Fragment>
);
};
Conclusion
Although the above have shown how we can change the way to handle input change by not using a ‘onChange’ method. It is better not to recommend imperatively update.
No Responses Yet