Mastering useRef in React for DOM manipulation

Mastering useRef in React — The Secret Weapon for DOM Manipulation When working with React, we often hear about state, props, and hooks like useState or useEffect. But there’s one hook that quietly powers some of the most efficient and interactive UI features — the underrated useRef. What is useRef? useRef is a React Hook that allows you to persist values across renders without causing re-renders. You can think of it as a “box” that holds a value — something that React doesn’t watch for updates. import { useRef } from "react"; function Example() { const countRef = useRef(0); const handleClick = () => { countRef.current += 1; console.log("Clicked", countRef.current, "times"); }; return <button onClick={handleClick}>Click Me</button>; } Here, countRef stores data between renders — but updating it won’t trigger re-render like useState does. Common Use Case — Accessing DOM Elements In React, we usually avoid directly touching the DOM, but sometimes — like when focusing an input field or controlling a video — it’s necessary. That’s where useRef shines. import { useRef, useEffect } from "react"; function FocusInput() { const inputRef = useRef(); useEffect(() => { inputRef.current.focus(); // directly access DOM element }, []); return <input ref={inputRef} placeholder="Auto-focused input" />; } Here, inputRef.current points to the actual DOM element, allowing us to perform actions like focus(), scrollIntoView(), or play(). Other Powerful useRef Use Cases 1. Store previous values — track changes between renders 2. Hold timers or intervals — clear them easily without re-renders 3. Integrate with third-party libraries (like chart or map APIs) 4. Prevent multiple API calls by tracking if a request is in progress useRef vs useState — Key Difference Feature useState useRef Triggers re-render ✅ Yes ❌ No Stores value persistently ✅ Yes ✅ Yes Ideal for UI state DOM refs, mutable data #ReactJS #useRef #JavaScript #FrontendDevelopment #WebDevelopment #ReactHooks #Programming #CodingTips #stemup

To view or add a comment, sign in

Explore content categories