What is useRef?
The useRef hook returns a mutable object that persists across renders. Unlike state variables, updating a useRef value does not cause a re-render of the component. This makes it ideal for storing values that need to persist between renders but don’t directly influence the UI.
const ref = useRef(initialValue);
- ref: The object returned by useRef. It has a current property that can be used to store a value.
- initialValue: The initial value assigned to the current property of the ref object.
import React, { useRef } from 'react';
function TextInput() {
const inputRef = useRef(null);
const focusInput = () => {
inputRef.current.focus();
};
return (
<div>
<input ref={inputRef} type="text" />
<button onClick={focusInput}>Focus Input</button>
</div>
);
}
Advantages of using useRef
- No Re-Renders: Updating a useRef value does not trigger a component re-render. This is crucial when you need to store information that should persist without affecting the component’s lifecycle.
- Accessing DOM Elements: useRef is the go-to solution for directly accessing and interacting with DOM elements in React.
- Storing Persistent Values: Use useRef to store values that need to persist across renders, like previous state values, timer IDs, or stable function references.
Conclusion
The useRef hook is a powerful and flexible tool in React, capable of handling various scenarios where state or props would be overkill or inappropriate. Whether you’re managing DOM elements, storing persistent values, or maintaining stable function references, understanding how to effectively use useRef can enhance your React applications and improve performance