The useRef
hook in React is used to create and manage mutable references to DOM elements or values within functional components. Unlike state, updates to a ref do not trigger a re-render, making useRef
useful for cases where you need to keep track of a value or reference without affecting the rendering lifecycle.
useRef
Creating a Ref:
useRef
is called with an initial value and returns a mutable object with a current
property.const myRef = useRef(initialValue);
import React, { useRef } from 'react';
function MyComponent() {
const inputRef = useRef(null);
const focusInput = () => {
inputRef.current.focus();
};
return (
<div>
<input ref={inputRef} type="text" />
<button onClick={focusInput}>Focus Input</button>
</div>
);
}
export default MyComponent;
Accessing DOM Elements:
useRef
is commonly used to access and manipulate DOM elements directly, such as focusing an input field or measuring the dimensions of an element.import React, { useRef, useEffect } from 'react';
function MyComponent() {
const divRef = useRef(null);
useEffect(() => {
console.log(divRef.current.getBoundingClientRect());
}, []);
return <div ref={divRef}>Hello, World!</div>;
}
export default MyComponent;
Storing Mutable Values:
useRef
can also be used to store mutable values that do not require triggering a re-render when they change. This is useful for keeping track of values across renders without causing performance issues.import React, { useRef, useState } from 'react';
function Timer() {
const [seconds, setSeconds] = useState(0);
const countRef = useRef(0);
const increment = () => {
countRef.current += 1;
setSeconds(countRef.current);
};
return (
<div>
<p>Seconds: {seconds}</p>
<button onClick={increment}>Increment</button>
</div>
);
}
export default Timer;
Avoiding Re-renders:
useRef
ideal for storing values that should persist across renders but do not need to cause re-renders.import React, { useRef, useState } from 'react';
function Example() {
const [count, setCount] = useState(0);
const renderCount = useRef(0);
renderCount.current += 1;
return (
<div>
<p>Current Count: {count}</p>
<p>Render Count: {renderCount.current}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}
export default Example;
Common Use Cases:
useRef
: A React hook that provides a way to create mutable references to DOM elements or values without triggering re-renders.const ref = useRef(initialValue);
The useRef
hook is a versatile tool in React that allows for efficient DOM manipulation and value persistence while avoiding unnecessary re-renders, helping to optimize the performance and manageability of functional components.
@aCodeTutorials All Rights Reserved
privacy policy | about