useRef Hook
What are useRef Hooks in React?
useRef is a React Hook that lets you reference a value that's not needed for rendering.It can also be used to access a DOM element directly.
Tip : This means , value changed does not cause a re-render.
The primary use cases for useRef includes:
Accessing DOM elements
One of the most common use cases of `useRef` is accessing DOM elements. Instead of using document.getElementById or other DOM queries, you can use useRef to directly reference an element within your component.
1import {useRef ,useState} from 'react';
2const App = () => {
3 const inputRef = useRef();
4 useEffect(() => {
5 //Focus on the input element when the component mounts
6 inputRef.current.focus();
7 },[]);
8 return <input ref={inputRef} />;
9};
10export default App;
Storing previous values
You can use useRef to store a value that persists across renders but doesn't trigger a re-render when updated. This can be useful when you need to keep track of previous values without triggering unnecessary renders.
1import { useRef, useEffect } from "react";
2const PrevValueApp = ({ value }) => {
3 const prevValueRef = useRef();
4 useEffect(() => {
5 prevValueRef.current = value;
6 }, [value]);
7 return (
8 <div>
9 <p>Current Value: {value}</p>
10 <p>Previous Value: {prevValueRef.current}</p>
11 </div>
12 );
13};
14export default PrevValueApp;
Tip : Also, note that `useRef` is not limited to working with DOM elements; it can be used for any mutable value that you want to persist across renders without causing re-renders.
Refinement
`useRef` is a powerful hook in React.js that enables developers to efficiently access and modify DOM elements, preserve values, and manage state without triggering unnecessary re-renders. Its versatility makes it an indispensable tool in a developer's toolkit, allowing for enhanced control and performance optimization in React applications. By mastering the use cases and practical implementations demonstrated in this article, developers can leverage the full potential of useRef to build more robust and efficient React components.