SyntaxStudy
Sign Up

useRef()

hook React 16.8

Returns a mutable ref object. Used to access DOM elements or store mutable values that do not trigger re-render.

Syntax

const ref = useRef(initialValue)

Example

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

function TextInput() {
    const inputRef = useRef(null);

    useEffect(() => {
        inputRef.current.focus(); // focus on mount
    }, []);

    return <input ref={inputRef} type="text" />;
}

// Store previous value
function usePrevious(value) {
    const ref = useRef();
    useEffect(() => { ref.current = value; });
    return ref.current;
}