</>
Skip to content
React lessons (21/47)

React — useRef

Basic useRef

import { useRef } from 'react';

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

    const focusInput = () => {
        inputRef.current.focus();
    };

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

useRef for Previous Value

function Counter() {
    const [count, setCount] = useState(0);
    const prevCount = useRef(count);

    useEffect(() => {
        prevCount.current = count;
    });

    return (
        <div>
            <p>Current: {count}</p>
            <p>Previous: {prevCount.current}</p>
            <button onClick={() => setCount(count + 1)}>Increment</button>
        </div>
    );
}

useRef for Timer

function Stopwatch() {
    const [time, setTime] = useState(0);
    const intervalRef = useRef(null);

    const start = () => {
        intervalRef.current = setInterval(() => {
            setTime(t => t + 1);
        }, 1000);
    };

    const stop = () => {
        clearInterval(intervalRef.current);
    };

    const reset = () => {
        clearInterval(intervalRef.current);
        setTime(0);
    };

    return (
        <div>
            <p>Time: {time}s</p>
            <button onClick={start}>Start</button>
            <button onClick={stop}>Stop</button>
            <button onClick={reset}>Reset</button>
        </div>
    );
}

useRef Examples

// Scroll to element
function ScrollToSection() {
    const sectionRef = useRef(null);

    const scrollToSection = () => {
        sectionRef.current.scrollIntoView({ behavior: 'smooth' });
    };

    return (
        <div>
            <button onClick={scrollToSection}>Scroll to Section</button>
            <div ref={sectionRef} style={{ height: '100vh' }}>
                <h2>Target Section</h2>
            </div>
        </div>
    );
}

// Store mutable value
function UseRefExample() {
    const renderCount = useRef(0);

    useEffect(() => {
        renderCount.current = renderCount.current + 1;
    });

    return <p>Rendered {renderCount.current} times</p>;
}

// Focus management
function Form() {
    const nameRef = useRef();
    const emailRef = useRef();

    const handleSubmit = (e) => {
        e.preventDefault();
        console.log(nameRef.current.value, emailRef.current.value);
    };

    return (
        <form onSubmit={handleSubmit}>
            <input ref={nameRef} placeholder="Name" />
            <input ref={emailRef} placeholder="Email" />
            <button type="submit">Submit</button>
        </form>
    );
}

Mini Practice

Write React code that:

  1. Uses useRef to access DOM element
  2. Stores previous value with useRef
  3. Manages timer with useRef
  4. Scrolls to element with useRef

Up Next

Next: Learn about useReducer hook.

Related Topics

Frequently Asked Questions about useRef

What is useRef in React?

useRef is a fundamental concept in React. This lesson explains it step by step with clear examples, making it easy for beginners to understand.

How do I learn useRef?

Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn useRef.

Why is useRef important in React?

useRef is essential for React development. Understanding this concept will help you write better code and solve real-world problems more effectively.