
The useRef Hook
19 January, 2023
0
0
0
Contributors
Introduction to the useRef
hook
The useRef
hook in React allows developers to access the underlying DOM element of a component. It is a way to store a reference to an element and access it throughout the lifetime of a component. The useRef
hook takes in an initial value and returns a mutable ref object which can be used to store the underlying DOM element. This allows developers to have direct access to the DOM element, making it easier to manipulate it, or access its properties or methods.
By using the useRef
hook, developers can make sure their React components are properly interacting with the underlying DOM elements.
Example of useRef
hook in React
Here's an example of how you might use the useRef
hook to create a reference to a DOM element in a component:
import { useRef } from 'react';
function MyComponent() {
const inputRef = useRef(null);
function handleClick() {
inputRef.current.focus();
}
return (
<>
<input ref={inputRef} />
<button onClick={handleClick}>Focus the input</button>
</>
);
}
In this example, the useRef
hook is used to create a inputRef
reference to an input
element. The reference is passed as the ref
prop to the input
element, so that its current
property will point to the actual DOM element.
In the handleClick
function, the focus
method of the DOM element is called, by accessing inputRef.current
which will give the dom node of the input field.
You can also use useRef to reference a component instance and keep track of some state that is not part of the component's props or state, like this:
import { useRef } from 'react';
function MyComponent() {
const myComponentRef = useRef(null);
function handleClick() {
myComponentRef.current.someMethod();
}
return (
<>
<MyChildComponent ref={myComponentRef} />
<button onClick={handleClick}>Call someMethod</button>
</>
);
}
In this example, you would reference your child component by passing the ref to it and then be able to call a custom method on it.
It's important to note that the value of a ref will not change between renders, making it ideal to store instances, dom nodes or timers/intervals ids as well as any other non-reactive value, like the previous state/props.
Conclusion
In summary, useRef
is a useful hook for cases where you need to directly manipulate the DOM or access the underlying instance of a component in your React application.