13 May 2024
useRef
hook provides a way to create a mutable reference that persists across renders. This reference can be used to interact with DOM elements directly or to persist values between renders without causing re-renders. Understanding how to use useRef
effectively can be valuable for various tasks in React development.useRef
hook:import React, { useRef } from 'react';
const MyComponent = () => {
const myRef = useRef(initialValue);
};
current
property:console.log(myRef.current);
myRef.current = newValue;
useRef
is accessing and manipulating DOM elements directly. This is useful for focusing inputs, measuring elements, or triggering imperative animations.import React, { useRef, useEffect } from 'react';
const MyComponent = () => {
const inputRef = useRef(null);
useEffect(() => {
inputRef.current.focus();
}, []);
return <input ref={inputRef} />;
};
useRef
is storing values between renders without triggering a re-render. This is useful for preserving state across renders, such as previous props or state values.import React, { useRef, useEffect } from 'react';
const MyComponent = ({ value }) => {
const previousValueRef = useRef();
useEffect(() => {
previousValueRef.current = value;
});
const previousValue = previousValueRef.current;
return <div>Previous value: {previousValue}</div>;
};
useRef
can also help avoid stale closures in event handlers or asynchronous functions. By storing the current value of a variable in a ref, you can ensure that the value remains up-to-date even if the function is called asynchronously.import React, { useState, useRef } from 'react';
const MyComponent = () => {
const [count, setCount] = useState(0);
const countRef = useRef(count);
useEffect(() => {
countRef.current = count;
}, [count]);
const handleClick = () => {
setTimeout(() => {
alert(`Count: ${countRef.current}`);
}, 1000);
};
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
<button onClick={handleClick}>Show Count</button>
</div>
);
};
useRef
hook in React is a powerful tool for interacting with DOM elements, storing values between renders, and avoiding stale closures. By understanding its usage and common use cases, you can leverage useRef
to enhance the functionality and performance of your React components. Whether you need to manipulate DOM elements, preserve state, or handle asynchronous operations, useRef
provides a versatile solution for many scenarios in React development.No data |