What is useRef?
The useRef hook in React is used to access and interact with DOM elements directly or to keep a mutable value that does not cause re-renders when changed. It provides a way to persist values across renders without triggering a component update.
How useRef Works
useRef returns a mutable object called a "ref object" with a .current property. This property can hold a value that persists across re-renders.
Basic Syntax
const myRef = useRef(initialValue); -
initialValue: The initial value for the ref object. This is optional.
Example 1: Accessing DOM Elements
In this example, we'll use useRef to access a DOM element directly.
- Create the Component
import React, { useRef, useEffect } from 'react'; const FocusInput = () => { // Create a ref with useRef const inputRef = useRef(null); useEffect(() => { // Focus the input field when the component mounts inputRef.current.focus(); }, []); return ( <div> <input ref={inputRef} type="text" placeholder="Focus me on mount" /> </div> ); }; export default FocusInput; Explanation:
-
useRef(null)creates a ref object. -
inputRef.currentgives access to the input element. -
useEffectis used to focus the input field when the component mounts.
Example 2: Keeping Mutable Values
In this example, we'll use useRef to keep a mutable value that does not cause re-renders when updated.
- Create the Component
import React, { useRef, useState } from 'react'; const Timer = () => { const [count, setCount] = useState(0); const timerRef = useRef(null); const startTimer = () => { if (timerRef.current) { clearInterval(timerRef.current); } timerRef.current = setInterval(() => { setCount(prevCount => prevCount + 1); }, 1000); }; const stopTimer = () => { if (timerRef.current) { clearInterval(timerRef.current); } }; return ( <div> <h1>Time: {count}s</h1> <button onClick={startTimer}>Start Timer</button> <button onClick={stopTimer}>Stop Timer</button> </div> ); }; export default Timer; Explanation:
-
timerRef.currentis used to store the timer ID. -
startTimerandstopTimerfunctions usetimerRef.currentto manage the timer. - Updating
timerRef.currentdoes not cause a re-render of the component.
Summary
-
useRefcreates a mutable ref object with a.currentproperty. - Use
useRefto access DOM elements directly. - Use
useRefto keep mutable values that do not cause re-renders.
That’s it! useRef is a powerful and versatile hook that’s useful in many scenarios.
Top comments (0)