📜  useRef - Javascript (1)

📅  最后修改于: 2023-12-03 15:20:55.361000             🧑  作者: Mango

useRef in Javascript

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.

Syntax
const refContainer = useRef(initialValue);
Usage
1. Referencing DOM elements

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>
    )
}
2. Storing mutable values

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>
    )
}
3. Storing previous props or state

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>
    )
}
Conclusion

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.