If you work with JavaScript long enough, you’ll eventually run into situations where a function gets called way too many times. Think about typing in a search bar, scrolling a page, or resizing a browser window. These events fire continuously, and if we trigger heavy logic every single time, the app can become slow pretty quickly. This is where debouncing and throttling come in. Debouncing waits for the user to finish doing something before running the function. A simple example is a search bar. Imagine an API call running on every keystroke while someone types “javascript”. That’s 10 API calls when we really only need one. With debouncing, the function runs only after the user stops typing for a short delay. So instead of triggering the search repeatedly, it waits until the typing pauses. Throttling works a little differently. It makes sure a function runs at most once in a fixed time interval, no matter how many times the event fires. Scrolling is a good example. When a user scrolls, the event can fire dozens of times per second. Throttling limits how often the logic runs, like once every 200ms, which keeps the UI responsive without overwhelming the browser. In simple terms: Debounce → run after the activity stops Throttle → run at regular intervals during the activity Both are small techniques, but they make a big difference when it comes to performance and user experience. #javascript #webdevelopment #frontenddevelopment #fullstackdeveloper #reactjs #devcommunity #programming
Optimizing Function Calls with Debouncing and Throttling in JavaScript
More Relevant Posts
-
Half the JavaScript your app ships is never used. Not on slow connections. Not on fast ones. Never. According to HTTP Archive's, the median page ships 613KB of JavaScript on desktop. Roughly half of it is never used during page load. What it does Code splitting divides your bundle into smaller chunks that load only when required. For example, one production React application reduced its bundle size from 2.3MB to 875KB and improved Time to Interactive from 5.2 seconds to 2.7 seconds. Where to split Routes — always first Heavy libraries — 200–500KB each Modals, drawers, PDF export — rarely used, no reason to preload Permission-based chunks — admin panels, billing, or internal tools, in bundles for users who cannot access them. This practice avoids unnecessary data transfer and potential security concerns. The trap I see most often Avoid splitting too aggressively at the component level, as it can lead to excessive network requests. Instead, split at logical boundaries that align with the user journey rather than the file structure. Code splitting is a simple yet significant technique. #Frontend #JavaScript #WebPerformance #React #CodeSplitting #WebDev #SoftwareEngineering #Programming
To view or add a comment, sign in
-
-
🚀 What is a Polyfill in JavaScript? (And why every frontend dev should care) Ever tried using a modern JS feature… and it just breaks in older browsers? 😅 That’s where Polyfills come in. 👉 A polyfill is a piece of code that adds support for features that a browser doesn’t natively support. 💡 Simple idea: “If the browser doesn’t support it, I’ll implement it.” 🔧 Example: Array.includes() polyfill if (!Array.prototype.includes) { Array.prototype.includes = function (value) { return this.indexOf(value) !== -1; }; } ✔️ Now even older browsers can use includes()! ⚙️ Why Polyfills Matter Ensure cross-browser compatibility Let you use modern JavaScript safely Critical for production-grade apps 🧠 Polyfill vs Transpiler Polyfill → Adds missing functionality Transpiler (Babel) → Converts modern syntax to older syntax 👉 You often need both in real-world apps. 📦 Pro Tip Instead of writing polyfills manually: Use core-js Use CDN like polyfill.io Let Babel handle it automatically ⚠️ Be mindful Polyfills can increase bundle size — use them only when necessary. 🔥 Takeaway Polyfills help you write modern code without breaking older environments — making your app more reliable and user-friendly. #JavaScript #WebDevelopment #Frontend #Coding #SoftwareEngineering #DevTips #100DaysOfCode #Programming #Tech #Developers
To view or add a comment, sign in
-
-
Blog 03 of my JS Unlocked series is live! 🚀 Control Flow in JavaScript: If, Else, and Switch Explained 👇 Every app makes decisions — show this page or that one, allow access or block it. That decision-making power in code is called control flow. In this one I cover: ✅ What control flow actually means ✅ if, if-else, and else if ladder with real examples ✅ switch statement — and why break matters ✅ When to use switch vs if-else (with a clear comparison) ✅ Hands-on challenge at the end Would love your feedback if you read it 🙏 🔗 https://lnkd.in/dSXtQpfS Thanks to #HiteshChoudhary Sir, #PiyushGarg💛 #JavaScript #WebDevelopment #Hashnode #WebDevCohort2026 #LearningInPublic #Frontend #JS
To view or add a comment, sign in
-
🔥 Why useEffect Runs Twice in React Strict Mode If you’ve seen this while developing with React: JSX code : useEffect(() => { console.log("Effect ran"); }, []); You expect this to run once. But in development, the console shows: Effect ran Effect ran So… is React broken? Not really. 🧠 What’s Actually Happening When React Strict Mode is enabled, React intentionally runs some lifecycle logic twice in development. This includes useEffect. Why? Because React is checking if your effects are safe and predictable. 🔍 What React Is Testing React wants to detect bugs like: Side effects that are not cleaned up Code that relies on running only once Hidden memory leaks To do that, React: 1️⃣ Mounts the component 2️⃣ Runs the effect 3️⃣ Immediately unmounts it 4️⃣ Mounts it again If your cleanup logic is correct, everything still works. ✅ Example with Cleanup JSX code useEffect(() => { const id = setInterval(() => { console.log("running"); }, 1000); return () => clearInterval(id); }, []); This ensures no leftover side effects. 🎯 Important Note This only happens in development. Production builds run effects normally. #ReactJS #FrontendDevelopment #JavaScript #ReactHooks #WebDevelopment #LearningInPublic
To view or add a comment, sign in
-
𝐀𝐫𝐞 𝐲𝐨𝐮𝐫 𝐮𝐬𝐞𝐄𝐟𝐟𝐞𝐜𝐭 𝐡𝐨𝐨𝐤𝐬 𝐫𝐮𝐧𝐧𝐢𝐧𝐠 𝐰𝐢𝐥𝐝? I just debugged a subtle React re-render loop that comes up more often than you'd think. Here's the trap: When you define an object or array directly inside your component's render function and then pass it as a dependency to `useEffect`. ```javascript function MyComponent() { const settings = { fetchLimit: 10, isActive: true }; useEffect(() => { // This effect will re-run on every render // because `settings` is a new object reference each time. fetchData(settings); }, [settings]); // 🚨 Problem here! // ... } ``` Even if the contents of `settings` are identical, its reference changes on every render. React sees a "new" dependency and re-runs your effect. Hello, infinite loops or wasted API calls! The fix? Stabilize your dependencies. Use `useMemo` if the object/array is derived from other stable props/state, or define it outside the component if it's truly constant. ```javascript function MyComponent() { const settings = useMemo(() => ({ fetchLimit: 10, isActive: true }), []); // ✅ Stabilized! useEffect(() => { fetchData(settings); }, [settings]); // Now `settings` reference is stable // ... } ``` This simple tweak can save a lot of head-scratching and dramatically improve performance. Always remember: `useEffect` compares dependencies by reference, not by value. What's your go-to strategy for taming `useEffect` dependency arrays? Share your tips! #React #Frontend #JavaScript #WebDevelopment #Performance
To view or add a comment, sign in
-
React Hooks changed the game by allowing us to use state and other features without writing classes. If you are building modern web apps, mastering these hooks is non-negotiable! 💻✨ Here is a quick guide to the most essential React Hooks and when to use them: 🔹 useState – The State Manager Purpose: Manages local component data. Use Cases: Form inputs, counters, toggles, or any dynamic UI updates. 🔹 useEffect – The Lifecycle Handler ⚡ Purpose: Handles side effects (actions outside React's control). Use Cases: API data fetching, setting up timers, or direct DOM manipulation. 🔹 useContext – The Prop-Drilling Killer 🛡️ Purpose: Shares data globally across the component tree. Use Cases: User authentication, Theme switching (Dark/Light mode), or Language settings. 🔹 useRef – The Persistent Reference Purpose: Grabs DOM elements or stores values without triggering a re-render. Use Cases: Focusing an input field, managing scroll positions, or storing previous state values. 🔹 useMemo – The Value Optimizer 🧠 Purpose: Remembers expensive calculation results. Use Cases: Filtering massive datasets or heavy mathematical computations. 🔹 useCallback – The Function Memorizer Purpose: Prevents functions from being recreated on every render. Use Cases: Passing stable functions to optimized child components to prevent lag. 🔹 useReducer – The Complex State Boss Purpose: Manages complex state logic (Redux-style). Use Cases: Multi-step forms or states where one update depends on another. ✨ Why Hooks Matter? Hooks don't just "make things work"—they make your code readable, reusable, and scalable. They separate concerns and keep your components clean. Which Hook do you find most challenging to master? Let's discuss in the comments! 👇 #ReactJS #WebDevelopment #Frontend #JavaScript #CodingTips #ReactHooks #SoftwareEngineering #Programming
To view or add a comment, sign in
-
-
🚀 What is Hydration in React? Hydration is one of those terms that sounds complex at first, but the idea behind it is actually simple. When we use Server Side Rendering (SSR), the server sends ready-made HTML to the browser. Because the HTML is already generated, the page appears on the screen very quickly. But at this moment, the page is only static — buttons don’t work, and there is no interaction yet. Then React loads the JavaScript bundle in the browser. After the JavaScript loads, React attaches event listeners and logic to the existing HTML. This process of connecting React with the already rendered HTML is called Hydration. 👉 In simple words: Hydration = React making server-rendered HTML interactive. ⚠️ Why does a Hydration Error happen? A hydration error happens when the HTML generated on the server is different from what React renders on the client. React tries to match both versions of the UI. If they don’t match, React throws a hydration error. Common reasons include: • Using Math.random() during rendering • Using Date.now() • Rendering content that depends on window or browser APIs • Conditional rendering that behaves differently on server and client 💡 Key Takeaway When working with SSR frameworks like Next.js, the initial UI generated on the server and the client must be the same. Otherwise, React cannot hydrate the page correctly. 💬 Have you ever faced a hydration error while working with React or Next.js? #React #NextJS #FrontendDevelopment #WebDevelopment #JavaScript #SoftwareEngineering #ReactJS #Coding #TechLearning
To view or add a comment, sign in
-
-
🚀 Understanding Class Components in React One concept that helped me understand how components work internally was Class Components. Before Hooks became popular, class components were the primary way to manage state and lifecycle methods in React applications. A class component is simply a JavaScript class that extends React.Component and must contain a render() method that returns JSX. Example: import React, { Component } from "react"; class Welcome extends Component { render() { return <h1>Hello World</h1>; } } export default Welcome; In class components: 🔹 Props are accessed using this.props 🔹 State is managed using this.state 🔹 State updates are done with this.setState() 🔹 Lifecycle methods like componentDidMount() allow us to run code when the component mounts, updates, or unmounts. Example with state: class Counter extends Component { state = { count: 0 }; increase = () => { this.setState({ count: this.state.count + 1 }); }; render() { return ( <button onClick={this.increase}> {this.state.count} </button> ); } } Today, most developers prefer Functional Components with Hooks like useState and useEffect, but understanding Class Components is still valuable because: ✅ Many legacy React projects still use them ✅ They help you understand React's lifecycle deeply ✅ Some interview questions still cover them Learning both approaches gives you a stronger foundation in React. Sometimes, understanding the old way helps you appreciate the modern way even more. #React #FrontendDevelopment #JavaScript #WebDevelopment #LearningInPublic
To view or add a comment, sign in
-
JavaScript events like scroll, resize, and typing can fire hundreds of times per second. If we run heavy functions on every event, the app can become slow and inefficient. Two common solutions to control this are: Debounce and Throttle Debounce Runs the function only after the event stops firing for a specific time. Example: Search input autocomplete. Throttle Runs the function at most once in a fixed time interval, even if the event keeps firing. Example: Scroll event handling. Quick difference: Debounce → waits for user inactivity Throttle → limits how often a function can run Using these techniques improves performance, user experience, and efficiency in real-world applications. Follow for more JavaScript concepts explained visually. 🚀 #javascript #webdevelopment #frontenddeveloper #coding #softwareengineering
To view or add a comment, sign in
-
-
🧠 React Concept: Why Closures Cause “Stale State” Bugs Sometimes React code looks correct… but the behavior is confusing. Example 👇 function Counter() { const [count, setCount] = React.useState(0); function handleClick() { setTimeout(() => { console.log(count); }, 2000); } return ( <div> <button onClick={() => setCount(count + 1)}>Increment</button> <button onClick={handleClick}>Log Count</button> </div> ); } Now imagine this: 1️⃣ Click Increment → count becomes 1 2️⃣ Click Log Count 3️⃣ Click Increment again → count becomes 2 After 2 seconds… The console prints: 1 Not 2. 🤔 Why? Because of JavaScript closures. When handleClick runs, it captures the value of count at that moment. React updates state later, but the closure still remembers the old value. ✅ Correct Solution Use a ref to access the latest state. const countRef = useRef(count); useEffect(() => { countRef.current = count; }, [count]); setTimeout(() => { console.log(countRef.current); }, 2000); Now the value stays up-to-date. 🎯 Key Takeaway Many React bugs are not React problems. They are JavaScript closure problems. Understanding this saves hours of debugging. #ReactJS #JavaScript #FrontendDevelopment #ReactHooks #WebDevelopment #CodingTips #LearningInPublic
To view or add a comment, sign in
Explore related topics
- Front-end Development with React
- Techniques For Optimizing Frontend Performance
- How to Ensure App Performance
- Debugging Tips for Software Engineers
- Improving App Performance With Regular Testing
- How to Optimize Your Website for User Experience
- How to Boost Web App Performance
- Tips for Optimizing App Performance Testing
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