📅  最后修改于: 2023-12-03 15:20:55.361000             🧑  作者: Mango
In React, useRef()
is a hook function that allows you to create and hold a reference to a mutable value that persists for the entire lifetime of a component. It can be used to reference DOM elements, store previous states or props, and much more. In this article, we will explore the many use cases of useRef
in Javascript.
const refContainer = useRef(initialValue);
One of the most common use cases of useRef
is to reference DOM elements. This is particularly useful when you need to access an element's properties or methods programmatically, such as setting focus, scrolling, or triggering events.
import { useRef } from 'react'
const App = () => {
const buttonRef = useRef(null);
const handleClick = () => {
buttonRef.current.disabled = true;
setTimeout(() => {
buttonRef.current.disabled = false;
}, 3000);
};
return (
<div>
<button onClick={handleClick} ref={buttonRef}>Click me!</button>
</div>
)
}
Another use case of useRef
is to store mutable values that won't trigger a re-render. Unlike state, updating a ref's value won't cause a component to re-render.
import { useRef } from 'react'
const App = () => {
const countRef = useRef(0);
const handleClick = () => {
countRef.current++;
console.log(countRef.current);
};
return (
<div>
<button onClick={handleClick}>Increment</button>
</div>
)
}
useRef
can also be used to store previous props or state values. This is particularly useful if you need to compare the current and previous values to determine if a certain action should be taken.
import { useRef, useEffect } from 'react'
const App = () => {
const prevCountRef = useRef(0);
const [count, setCount] = useState(0);
useEffect(() => {
prevCountRef.current = count;
}, [count]);
const handleButtonClick = () => {
if (count > 0 && count > prevCountRef.current) {
console.log('Count increased');
}
setCount(count + 1);
};
return (
<div>
<p>Count: {count}</p>
<button onClick={handleButtonClick}>Increment</button>
</div>
)
}
In conclusion, useRef
is a powerful tool in the React developer's toolbox with many use cases. We covered a few common examples above, but there are many more to explore. Remember that the value of a ref persists for the entire lifetime of a component, making it an excellent choice for storing mutable data that doesn't require re-rendering.