Skip to content
React

useRef

Reference DOM and mutable values.

By EZ4Code Team
reacthook

Code

import { useRef, useState, useEffect } from 'react';

// DOM reference
function FocusInput() {
    const inputRef = useRef(null);

    const focus = () => inputRef.current.focus();

    return (
        <div>
            <input ref={inputRef} type="text" />
            <button onClick={focus}>Focus</button>
        </div>
    );
}

// Mutable value (no re-render)
function Stopwatch() {
    const [seconds, setSeconds] = useState(0);
    const timerRef = useRef(null);

    const start = () => {
        timerRef.current = setInterval(() => {
            setSeconds(s => s + 1);
        }, 1000);
    };

    const stop = () => clearInterval(timerRef.current);

    useEffect(() => () => clearInterval(timerRef.current), []);

    return (
        <div>
            <p>{seconds}s</p>
            <button onClick={start}>Start</button>
            <button onClick={stop}>Stop</button>
        </div>
    );
}

// Get previous value
function usePrevious(value) {
    const ref = useRef();
    useEffect(() => {
        ref.current = value;
    }, [value]);
    return ref.current;
}

// Keep reference across renders
function Component() {
    const mapRef = useRef(new Map());

    const addItem = (key, value) => {
        mapRef.current.set(key, value);
    };

    return <div>{mapRef.current.size} items</div>;
}

Explanation

useRef references DOM elements or holds mutable values; modifying .current doesn't trigger re-renders; suitable for storing timers, etc.

More React Snippets