React ~ Hooks ~ useRef - rohit120582sharma/Documentation GitHub Wiki

The purpose of useRef hook is allow you to persist a value across renders. But unlike useState, it won't trigger a re-render of the component.

useRef returns a mutable ref object whose current property is initialized to the passed argument (initialValue). The returned object will persist for the full lifetime of the component and anything you add to current will be persisted across renders.

The most popular use case for useRef is getting access to DOM nodes. If you pass the value you get from useRef as a ref prop on any React element, React will set the current property to the corresponding DOM node. This allows you to do things like grab input values or set focus.


function Counter() {
    const [count, setCount] = React.useState(0);
    const id = React.useRef(null); // { current: null }

    const clearInterval = () => {
        window.clearInterval(id.current);
    }

    useEffect(() => {
        id.current = window.setInterval(() => {
            setCount(c => c + 1);
        }, 1000);

        return clearInterval;
    }, [id]);

    return (
        <div>
            <h1>{count}</h1>
            <button onClick={clearInterval}>Stop</button>
        </div>
    );
}

function Form () {
    const nameRef = React.useRef();
    const passwordRef = React.useRef();

    const handleSubmit = (e) => {
        e.preventDefault();

        const name = nameRef.current.value;
        const password = passwordRef.current.value;

        console.log(name, password);
    }
    const handleReset = () => {
        nameRef.current.value = '';
        passwordRef.current.value = '';
    }

    return (
        <React.Fragment>
            <label>
                Name:
                <input
                    type='text'
                    placeholder='Name'
                    ref={nameRef} />
            </label>
            <label>
                Password:
                <input
                    type='text'
                    placeholder='Password'
                    ref={passwordRef} />
            </label>

            <hr />
            <button onClick={() => nameRef.current.focus()}>Focus Name Input</button>
            <button onClick={() => passwordRef.current.focus()}>Focus Password Input</button>

            <hr />

            <button onClick={handleSubmit}>Submit</button>
            <button onClick={handleReset}>Reset</button>
        </React.Fragment>
    );
}
⚠️ **GitHub.com Fallback** ⚠️