How to Use useRef in React for Efficient Coding

⚡ React Tip: Use useRef When You Don’t Want Re-Renders Not every piece of data in React needs to trigger a re-render. That’s where the useRef hook shines. 💡 Think of useRef as a box that holds a value — and React doesn’t care what’s inside. It’s perfect for storing values that change but don’t affect the UI. import { useRef, useState } from "react"; function Timer() {  const [count, setCount] = useState(0);  const intervalRef = useRef(null); // 👈 No re-renders  const start = () => {   if (intervalRef.current) return; // prevent multiple intervals   intervalRef.current = setInterval(() => {    setCount((c) => c + 1);   }, 1000);  };  const stop = () => {   clearInterval(intervalRef.current);   intervalRef.current = null;  };  return (   <div>    <p>⏱️ Count: {count}</p>    <button onClick={start}>Start</button>    <button onClick={stop}>Stop</button>   </div>  ); } ✅ Why it’s awesome: 1. Doesn’t cause re-renders when updated 2. Great for storing timers, previous values, or DOM references 3. Keeps your component efficient and smooth 💭 Remember: Use useRef for mutable values that shouldn’t trigger renders. Use useState for UI values that should. How often do you reach for useRef in your projects? 👇 #ReactJS #JavaScript #WebDevelopment #FrontendTips #CodingTips #CleanCode #ReactHooks #Programming #WebDev #TechTips

To view or add a comment, sign in

Explore content categories