React useRef Explained: No Re-render

🧠 Why useRef Doesn’t Cause a Re-render in React Many developers assume useRef behaves like state. But it doesn’t. Example 👇 function Counter() { const countRef = useRef(0); function increment() { countRef.current += 1; console.log(countRef.current); } return ( <button onClick={increment}> Count: {countRef.current} </button> ); } Click the button. Console shows: 1 2 3 But the UI still shows: Count: 0 🔍 Why? useRef does not trigger a re-render. Updating: countRef.current = newValue changes the value, but React does not re-run the component. 🧠 What useRef Is Actually For useRef is mainly used for: Accessing DOM elements Persisting values between renders Storing mutable data that shouldn’t trigger UI updates Example: const inputRef = useRef(); <input ref={inputRef} /> 🎯 Key Rule If the UI needs to update → use state If the value just needs to persist → use ref #ReactJS #FrontendDevelopment #JavaScript #ReactHooks #WebDevelopment #LearningInPublic

To view or add a comment, sign in

Explore content categories