𝐓𝐡𝐢𝐧𝐤𝐢𝐧𝐠 `useRef` 𝐢𝐬 𝐨𝐧𝐥𝐲 𝐟𝐨𝐫 𝐃𝐎𝐌 𝐞𝐥𝐞𝐦𝐞𝐧𝐭𝐬 𝐢𝐧 𝐑𝐞𝐚𝐜𝐭? 𝐘𝐨𝐮'𝐫𝐞 𝐦𝐢𝐬𝐬𝐢𝐧𝐠 𝐨𝐮𝐭 𝐨𝐧 𝐚 𝐩𝐨𝐰𝐞𝐫𝐟𝐮𝐥 𝐨𝐩𝐭𝐢𝐦𝐢𝐳𝐚𝐭𝐢𝐨𝐧 𝐭𝐫𝐢𝐜𝐤. Many developers stop at `useRef` for getting a handle on a DOM node. But its real magic lies in its ability to persist any mutable value across renders without triggering a re-render itself. Think of it as an instance variable for your function component. Unlike `useState`, which re-renders your component when its value changes, updating `ref.current` is silent to React's rendering cycle. This is critical for scenarios like: * Storing a timer ID (`setTimeout`, `setInterval`) that you need to clear later. * Keeping track of a previous prop or state value for comparison. * Holding an expensive object or an external library instance that doesn't need to be part of the component's reactive state. ```jsx function MyComponent() { const countRef = useRef(0); // This won't trigger re-renders const [countState, setCountState] = useState(0); // This will const incrementRef = () => { countRef.current += 1; console.log('Ref Count:', countRef.current); // Updates, but UI doesn't re-render solely from this }; const incrementState = () => { setCountState(prev => prev + 1); // Updates and re-renders UI }; return ( <div> <p>Ref Count: (Check console, UI needs another render trigger)</p> <p>State Count: {countState}</p> <button onClick={incrementRef}>Increment Ref</button> <button onClick={incrementState}>Increment State</button> </div> ); } ``` `useRef` is your quiet workhorse for mutable, non-reactive data. It helps you manage side effects and optimize renders by keeping certain values out of the state-driven re-render loop. What's your favorite non-DOM use case for `useRef`? Share your clever hacks! #React #FrontendDevelopment #JavaScript #WebDev #ReactHooks
Unlock useRef's Power Beyond DOM Elements
More Relevant Posts
-
🚀 Day 8 Not Just Motivation — Real Concepts to Build Strong Technical Understanding (Part 8) Why does JavaScript remember variables even after a function finishes? The answer is Closure. Let’s understand this using a real-world example from React: useState. A simplified mental model of useState (conceptual) function useState(initialValue) { let state = initialValue; function setState(newValue) { state = newValue; render(); // re-render component } return [state, setState]; } Here, setState is a closure. It remembers state even after useState finishes execution. Example: Counter Component function Counter() { const [count, setCount] = React.useState(0); return ( <button onClick={() => setCount(count + 1)}> Count: {count} </button> ); } Every render is a new function call. So how does React remember count? Let’s go step by step. Render 1 – Initial Mount 1. React calls the component: Counter(). 2. useState(0) runs and creates a state slot outside the function (heap/fiber). 3. count is set to 0 and setCount is returned as a closure. 4. JSX is rendered and UI shows Count: 0. User Clicks the Button 1. Browser triggers a click event. 2. React handles the event via its synthetic event system. 3. setCount(count + 1) is called. 4. React updates internal state and schedules a re-render. Render 2 – After State Update 1. Counter() runs again. 2. Local variables are recreated, but state is preserved. 3. useState does not reinitialize; it reads existing state from memory. 4. count is now 1 and UI updates accordingly. Final Takeaway The component function re-runs on every render, but state survives because React stores it outside the function. setState works because it is a closure pointing to that preserved state. Closures are the reason useState works. #javascript #closure #reactjs #reacthooks #frontend #webdevelopment
To view or add a comment, sign in
-
𝗨𝗻𝗱𝗲𝗿𝘀𝘁𝗮𝗻𝗱𝗶𝗻𝗴 𝗛𝗶𝗴𝗵𝗲𝗿 𝗢𝗿𝗱𝗲𝗿 𝗖𝗼𝗺𝗽𝗼𝗻𝗲𝗻𝘁𝘀 (𝗛𝗢𝗖) 𝗶𝗻 𝗥𝗲𝗮𝗰𝘁 Ever wondered how to reuse logic and structure across multiple components without repeating code? That’s where Higher Order Components (HOC) come in. 𝗪𝗵𝗮𝘁 𝗶𝘀 𝗮 𝗛𝗶𝗴𝗵𝗲𝗿 𝗢𝗿𝗱𝗲𝗿 𝗖𝗼𝗺𝗽𝗼𝗻𝗲𝗻𝘁? A Higher Order Component is a function that takes a component as input and returns a new enhanced component with additional functionality. In simple words: 𝘏𝘖𝘊 = 𝘧𝘶𝘯𝘤𝘵𝘪𝘰𝘯(𝘊𝘰𝘮𝘱𝘰𝘯𝘦𝘯𝘵) → 𝘌𝘯𝘩𝘢𝘯𝘤𝘦𝘥𝘊𝘰𝘮𝘱𝘰𝘯𝘦𝘯𝘵 𝗪𝗵𝘆 𝗱𝗼 𝘄𝗲 𝘂𝘀𝗲 𝗛𝗢𝗖𝘀? To follow the 𝗗𝗥𝗬 principle — “Don’t Repeat Yourself”. When multiple components need the same logic or structure, instead of duplicating code, we can wrap them with an HOC and reuse the behavior cleanly. 𝗕𝗲𝗻𝗲𝗳𝗶𝘁𝘀 𝗼𝗳 𝘂𝘀𝗶𝗻𝗴 𝗛𝗢𝗖𝘀 • Code reusability • Cleaner and more modular code • Better separation of concerns • Consistent behavior across components • Industry-standard pattern used in large React codebases 𝗥𝗲𝗮𝗹-𝘄𝗼𝗿𝗹𝗱 𝗲𝘅𝗮𝗺𝗽𝗹𝗲 In one of my applications, Navbar, Sidebar, and Footer were required on almost every page. Instead of manually adding these components to every page: I created a Layout HOC that includes Navbar, Sidebar, and Footer Then I passed each screen/page component into that HOC So the result became: (𝘓𝘢𝘺𝘰𝘶𝘵 𝘏𝘖𝘊 + 𝘗𝘢𝙜𝘦 𝘊𝘰𝘮𝘱𝘰𝘯𝘦𝘯𝘵) → 𝘕𝘢𝘷𝘣𝘢𝘳 + 𝘚𝘪𝘥𝘦𝘣𝘢𝘳 + 𝘍𝘰𝘰𝘵𝘦𝘳 + 𝘗𝘢𝙜𝘦 𝘊𝘰𝘯𝘵𝘦𝘯𝘵 This made the codebase cleaner, easier to maintain, and scalable. 𝗪𝗵𝗲𝗻 𝘁𝗼 𝘂𝘀𝗲 𝗛𝗢𝗖𝘀? • When multiple components share the same logic. • When you want to add cross-cutting features like authentication, layouts, logging, or permissions. • When you want reusable and maintainable React architecture. Note: In modern React, hooks and layout components are often preferred, but HOCs are still widely used and important to understand — especially in real-world and legacy projects. Would love to hear your thoughts or real-world use cases of HOCs #React #JavaScript #FrontendDevelopment #WebDevelopment #ReactJS
To view or add a comment, sign in
-
-
React Batching = 1 render. Before React 18 (React 17 & earlier) React only auto-batched state updates inside React event handlers (like onClick, onChange). Multiple setState calls in the same handler = 1 re-render so that is great for these usages. But on the other hand => (setTimeout / setInterval , Promise.then / async await,addEventListener and useEffect callbacks somtimes) React doesn't patching all in one render and Each setState triggered a separate re-render and the result be unnecessary renders that cause wasted CPU and laggy lists, forms, loaders, modals, etc. Started from React 18 everything has changed with (createRoot) 1-Automatic batching now happens almost everywhere! 2-All updates in the same event loop / microtask get grouped once for single re-render. Examples: // Click handler (always batched, even before) const handleClick = () => { setCount(c => c + 1); setLoading(true); // 1 render (same as before) }; // Async fetch – previously 2 renders, now 1! const handleFetch = async () => { const data = await fetchData(); setData(data); setLoading(false); // 1 render in React 18 }; // setTimeout – previously 2 renders, now 1! setTimeout(() => { setCount(c => c + 1); setFlag(true); }, 0); // 1 render that is okay but what if we have a case that need to separate the renders then we need to use flushSync from 'react-dom' and wrap the state with it to ensure separated renders. Example: flushSync(() => { setCount(c => c + 1); }); Hope it was helpful! #React #React18 #JavaScript #Frontend #WebDev #Performance #ReactJS #FrontendDevelopment
To view or add a comment, sign in
-
-
Stop treating the JavaScript Event Loop like "Async Magic." Most of us use async/await, Promises, and setTimeout daily. Yet, we still encounter "mysterious" UI freezes and wonder why our code isn’t behaving as expected. The hard truth? Async code does NOT mean non-blocking UI. The browser doesn’t run your async code in parallel; it’s a single-threaded orchestrator scheduling work in a specific order. If you don't understand this order, you're likely writing bugs you can't see. The Hierarchy of Operations: 1. Call Stack: Your synchronous code always goes first. 2. Microtasks: Promises and async/await move to the front of the line. 3. Rendering: The browser attempts to update the UI. 4. Macrotasks: setTimeout and DOM events wait for all other tasks to finish. Three Common Misconceptions that Kill Performance: - "Async code is non-blocking." Wrapping a heavy for-loop in an async function doesn't make it faster; it still runs on the main thread. Heavy tasks will freeze the UI. - "setTimeout(fn, 0) is immediate." It’s not. It’s a way of saying, "I’ll wait until the stack is clear AND the browser has had a chance to render." It yields control, not speed. - "Promises are always safe." Microtasks (Promises) can "starve" the rendering process. The event loop processes the entire microtask queue before moving to rendering, which can lock your UI indefinitely. The Bottom Line: Frameworks like React, Angular, and Vue are not magic; they efficiently manage these queues. If your animations are lagging or your clicks feel unresponsive, examine your execution order rather than just your logic. The Golden Rule: Good frontend engineers write code that works. Great ones understand when the browser is allowed to breathe. #JavaScript #WebDevelopment #Frontend #WebPerformance #SoftwareEngineering #CodingTips
To view or add a comment, sign in
-
-
🧠 Is setState 𝘀𝘆𝗻𝗰𝗵𝗿𝗼𝗻𝗼𝘂𝘀 or 𝗮𝘀𝘆𝗻𝗰𝗵𝗿𝗼𝗻𝗼𝘂𝘀 in React? Short answer 👉 setState is 𝗮𝘀𝘆𝗻𝗰𝗵𝗿𝗼𝗻𝗼𝘂𝘀 — by design. React doesn’t update state immediately. Instead, it schedules state updates and batches multiple updates together to avoid unnecessary re-renders and improve performance. 𝘌𝘹𝘢𝘮𝘱𝘭𝘦:– setCount(count + 1); console.log(count); 𝘖𝘶𝘵𝘱𝘶𝘵:- 0 𝗪𝗵𝘆? Because setState does not update the value instantly — the current render still holds the old state. 🔁 𝗕𝗮𝘁𝗰𝗵𝗶𝗻𝗴 𝗶𝗻 𝗮𝗰𝘁𝗶𝗼𝗻 setCount(count + 1); setCount(count + 1); 𝗥𝗲𝘀𝘂𝗹𝘁 👉 1 (not 2) Both updates read the same stale state, and React batches them into a single render. ✅ The correct pattern (when state depends on previous state) setCount(prev => prev + 1); setCount(prev => prev + 1); 𝗥𝗲𝘀𝘂𝗹𝘁: 2 This works because React provides the latest queued state to each update. 🧠 𝗞𝗲𝘆 𝘁𝗮𝗸𝗲𝗮𝘄𝗮𝘆 setState doesn’t change state immediately. It requests a state change — React decides when to apply it. This behavior enables better performance, smoother UI, and concurrent rendering. 👀 𝗕𝘂𝘁 𝗵𝗲𝗿𝗲’𝘀 𝘁𝗵𝗲 𝘁𝘄𝗶𝘀𝘁... 👉 setState can be synchronous in React — but only in very specific situations and for a specific purpose. I’ll cover when, why, and whether you should ever use it in my next post. Stay tuned 🚀 #ReactJS #JavaScript #Frontend #WebDevelopment #ReactHooks #Performance #SoftwareEngineering
To view or add a comment, sign in
-
-
🚀 𝗥𝗲𝗮𝗰𝘁’𝘀 𝗛𝗶𝗱𝗱𝗲𝗻 𝗛𝗶𝘀𝘁𝗼𝗿𝘆: 𝗙𝗿𝗼𝗺 𝗫𝗛𝗣 𝘁𝗼 𝘁𝗵𝗲 𝗩𝗶𝗿𝘁𝘂𝗮𝗹 𝗗𝗢𝗠 Deep React understanding starts under the hood. Strong JavaScript and DOM fundamentals unlock: component-based architecture, reusable UI, declarative code, and scalable SPAs. 𝗪𝗵𝗲𝗿𝗲 𝗥𝗲𝗮𝗰𝘁 𝗰𝗼𝗺𝗲𝘀 𝗳𝗿𝗼𝗺 𝗺𝗮𝘁𝘁𝗲𝗿𝘀. 2010 — XHP A PHP extension that made XML valid PHP. Custom UI elements. Built-in XSS protection. Safer rendering. The problem: Dynamic apps meant frequent server round-trips. Small changes often triggered full UI re-renders. FaxJS An internal prototype by Jordan Walke, inspired by XHP. 2013 — React The Virtual DOM changed how UI updates are modeled and optimized. Tutorials are everywhere. But in the rush from vanilla JS → React → Next.js, clarity is often skipped. One resource still stands out: 📘 “Thinking in React” — react.dev A patient read that builds the right mental model: components, state, props, data flow, and SPA design—clearly and correctly. What’s the one React resource that actually improved how you think? 👇 #ReactJS #Frontend #WebDev #JavaScript #ThinkingInReact
To view or add a comment, sign in
-
-
Frontend performance is often discussed using scores. - Lighthouse. Core Web Vitals. Numbers. But performance problems don’t start with metrics. They start with work. The browser does work when it: - parses files - executes JavaScript - recalculates layout - paints pixels - responds to input When a page feels slow, it’s usually because too much work is happening on the main thread at the wrong time. A high Lighthouse score can still hide: - unnecessary re-renders - heavy synchronous JavaScript - layout thrashing - event handlers doing more than they should optimizing performance by chasing metrics often leads to accidental fixes. things feel faster, but the underlying cause is still there. A better question than “what’s the score?” is: - what work is the browser doing, and why now? Once you can answer that, the optimizations stop feeling like tricks. #frontend #react #javascript
To view or add a comment, sign in
-
Vite 7 Moves to Rolldown and Raises the Baseline Vite 7 is a quiet but decisive shift toward stability and predictability in frontend tooling. The move to Rolldown, a Rust-based bundler, signals where Vite is headed. Faster builds, lower overhead and more consistent behavior arrive without changing how most teams write code. It is an internal change with very visible day-to-day impact. Dropping Node 18 and standardizing on Node 20 cleans up years of compatibility weight. At the same time, switching default browser targets to baseline-widely-available trades optimism for realism. What works locally is far more likely to work for real users. Add the new Vite DevTools, and the picture becomes clear. Vite is choosing clarity over magic, discipline over shortcuts and long-term trust over novelty. This is not about adding more features. It is about tightening the foundation. https://lnkd.in/gBwhX2ZN #Vite #Vite7 #Frontend #BuildTools #WebDevelopment #JavaScript #Rust #DeveloperExperience
To view or add a comment, sign in
-
Debouncing vs. Throttling: The Secret to Smoother Web Experiences Ever typed in a search bar that lags like crazy? Or scrolled through a page where your browser fires off a million events? 😩 We've all been there. The fix? Debouncing or throttling. These JavaScript techniques can make your apps feel lightning-fast and user-friendly. Let me break it down simply: ⏳ Debouncing: "Wait until the user stops typing." It groups multiple events into one, executing only after a pause. Perfect for: Search bars (no more spamming API calls mid-type!) Form validation Window resize events 🚦 Throttling: "Do the action at most once every X milliseconds." It limits how often a function runs, no matter how many times it's triggered. Ideal for: Scroll events Infinite scrolling Dragging elements Quick rule of thumb: Typing or input-heavy? Debounce it. Continuous actions like scrolling? Throttle away. Your users (and your performance metrics) will love you for it! What's your go-to use case for these? Have you run into a tricky scenario where one worked better than the other? Share in the comments I'd love to hear your stories and tips! 👇 #JavaScript #FrontendDevelopment #ReactJS #WebDev #ProgrammingTips
To view or add a comment, sign in
-
Do you do this in your UI components or any use case? 👀 Using if / else inside a function to decide what to render or what to return isn’t wrong, especially for simple or one-off logic. But when the output is predictable (status codes, enums, types, variants, modes, roles, etc.), a data-driven mapping often scales better. By moving UI decisions into an object map: • the intent is clearer • the component stays cleaner • adding new cases doesn’t mean adding more branches This is just a basic example (status), the same pattern applies to any predictable case like role, type, variant, mode, step, state, and more. Conditionals are fine but when your UI grows, declarative mappings keep things easier to read and maintain. This pattern isn’t limited to frontend UI. The same idea applies in full-stack or backend code. #TypeScript #JavaScript #React #Frontend #CleanCode #UIEngineering #WebDevelopment #ProgrammingTips #ReactJS #NextJS #FullStack #Backend
To view or add a comment, sign in
-
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development