Hello everyone, I’d like to explain two JavaScript concepts—currying and closures—using the dynamic onChange handler in the code snippet below. Here’s a breakdown of how and why it works: 💡 The Concept: Instead of a standard function, we create a function that returns another function. 🧠 What is happening under the hood? 1. Currying (The Setup): We don't pass all arguments (field and e) at once. First, we call handleInputChange('email'). Result: This returns a new function that is sitting there, waiting specifically for the event e. 2. Closure (The Memory): Even after that first function finishes running, the returned function "remembers" the field variable ('email') because of closure. The Payoff: When React finally triggers the onChange event, our inner function executes with access to both the specific field name (saved from the closure) and the event (provided by React). One handler. Infinite inputs. Cleaner code. 🚀 Check out the implementation below. Have you used this pattern in your projects, or do you prefer a different approach? #JavaScript #ReactJS #WebDevelopment #CodingTips #CleanCode
Currying and Closures in JavaScript with React
More Relevant Posts
-
Ever wondered how JavaScript remembers variables even after a function has finished execution? It's The magic of Closure. A closure gives a function access to its outer scope. In JavaScript, closures are created every time a function is created, at function creation time. Example: function outer() { let count = 0; return function inner() { count++; console.log(count); }; } const counter = outer(); counter(); Result => 1 counter(); Result => 2 counter(); Result => 3 Explanation: Inner function remembers count from outer. Every time you call counter(), it retains the previous value. Usefulness of Closure: => Data encapsulation (private variables) => Memoization / caching => Event handlers & async callbacks Do you use closures in your projects? Share your use case below! #JavaScript #WebDevelopment #Closures #ReactJS #NexjJS #MERNStack #CodingTips
To view or add a comment, sign in
-
-
Are you accidentally slowing down your JavaScript applications? It’s a common mistake I see in code reviews (and one I’ve made myself). When dealing with multiple independent asynchronous calls, it feels natural to just await them one by one. But as the image on the left illustrates, this creates a "waterfall" effect. Your code has to wait for the first operation to finish before it can even start the second one. ✅ The Better Way: Parallel Execution The solution, shown on the right, is Promise.all(). This function takes an array of promises and fires them off simultaneously. Instead of waiting for the sum of all request times (e.g., 2s + 2s = 4s), you only wait for the slowest single request (e.g., max(2s, 2s) = ~2s). This simple change can drastically improve the performance and user experience of your application. A quick rule of thumb: If the data from request A isn't needed to make request B, they should be running in parallel. Have you caught yourself making this mistake? What’s your favorite JS performance tip? Let me know in the comments! 👇 #JavaScript #WebDevelopment #FrontendDeveloper #CodingTips #SoftwareEngineering #PerformanceOptimization
To view or add a comment, sign in
-
-
#Day 58/100 – Why JavaScript is Single-Threaded (and why that’s actually powerful) ⚡ When I first heard “JavaScript is single-threaded” I thought… Wait — only one thing at a time? Isn’t that slow? But today I understood something important. JavaScript being single-threaded is not a weakness. It’s the reason the web feels smooth. Imagine editing a form and suddenly the page freezes because 5 things run at once. That would be chaos. Instead, JavaScript follows a rule: Do one thing clearly, finish it, then move to the next. This makes UI predictable and prevents race conditions. But then how do videos load, APIs fetch data, and timers run? Because the browser handles heavy work in the background and JavaScript handles the result when it’s ready. So JS stays simple. The browser stays powerful. Big realization 💡 JavaScript isn’t trying to do everything at once — it’s trying to do everything in order. And that’s why websites don’t constantly break. Today I stopped thinking “single-threaded = limitation” Now I see “single-threaded = stability” #100DaysOfCode #JavaScript #WebDevelopment #LearningInPublic #FrontendDevelopment #CodingJourney
To view or add a comment, sign in
-
-
In React, a Hook is just a JavaScript object. Each Hook stores: the state value a queue of updates and a reference to the next Hook Internally it looks like this: { memoizedState: state, queue: updates, next: nextHook } React stores Hooks as a linked list attached to the component's Fiber node. Fiber → Hook → Hook → Hook → null This is why Hooks must always be called in the same order. React reads them one by one during every render. When you call setState, React adds the update to the Hook's queue, and processes it during the next render. Hooks are not magic. They are simple objects connected together. Understanding this helps explain many React behaviors. #reactjs #javascript #webdevelopment
To view or add a comment, sign in
-
-
🤯 Do you want a pro React tip? I started naming my useEffect functions, and its beautiful 👇 React code is full of hooks noise like useState, useEffect, useRef, and useMemo everywhere. It's hard to quickly scan a file and understand what's actually happening because the lifecycle stuff dominates everything. I started using named functions instead of arrow functions for my effects, and it made a massive difference. Here's why: 1️⃣ Cuts through the noise — When you have multiple useEffects in a component, descriptive names like synchronizeMapZoomLevel or fetchUserData let you scan the file and immediately understand the flow without reading implementation details. 2️⃣ Stack traces — If something breaks, the function name shows up in the error stack. Way easier to debug than an anonymous function at line 47. 3️⃣ Forces single responsibility — When you try to name an effect and struggle? That's usually because it's trying to do too many things. It naturally pushes you to split things up or remove them altogether (You might not need an effect) Some people prefer to extract everything into custom hooks immediately, which is great too. But this works really well for simpler cases where a full hook feels like overkill. Have you tried this? Or do you go straight to custom hooks for everything? #React #JavaScript #WebDev #CleanCode
To view or add a comment, sign in
-
-
React doesn't update the entire page. It's way smarter than that. Here's what actually happens behind the scenes in 6 simple steps: 📋 Virtual DOM — a lightweight JS copy of the real DOM 🔍 Diffing — comparing old vs new to spot changes 🔄 Reconciliation — the full compare-and-update cycle ✏️ JSX — looks like HTML, but it's JavaScript 🔧 Babel — translates JSX into plain JS before the browser sees it 🚀 The Flow — JSX → Babel → Virtual DOM → Diff → Real DOM Save this. The next part covers Components, Props & State. ♻️ Repost to help someone learning React. #React #VirtualDOM #JavaScript #WebDevelopment #Frontend #LearnToCode
To view or add a comment, sign in
-
-
🧩 JavaScript Output-Based Question (this + setTimeout) ❓ What will be the output? 👉 Comment your answer below (Don’t run the code ❌) Output: undefined 🧠 Why this output comes? (Step-by-Step) 1️⃣ print() is called as a method obj.print(); So inside print, this correctly refers to obj. 2️⃣ But inside setTimeout… setTimeout(function () { console.log(this.name); }, 0); The callback is a regular function, not a method of obj. When it executes: • this does NOT refer to obj • In non-strict mode → this points to the global object • In strict mode → this is undefined Either way: this.name → undefined 3️⃣ The key mistake ❌ Assuming this is preserved automatically in async callbacks 🔑 Key Takeaways ✔️ this depends on how a function is called ✔️ setTimeout callbacks lose object context ✔️ Use arrow functions or .bind() to fix this ✔️ This bug appears frequently in real projects #JavaScript #ThisKeyword #AsyncJavaScript #setTimeout #InterviewQuestions #FrontendDeveloper #MERNStack #ReactJS
To view or add a comment, sign in
-
-
Today I learned how useEffect cleanup actually works in React — and it completely changed how I think about side effects. When we use useEffect, it runs after render. But what many beginners ignore is the cleanup function. Why is cleanup important? Prevents memory leaks Stops unnecessary API calls Removes event listeners properly Clears intervals and timeouts Example: When you add an event listener inside useEffect, you must remove it when the component unmounts. Otherwise, it keeps running in the background. That’s where cleanup comes in. useEffect(() => { const handleResize = () => console.log("Resized"); window.addEventListener("resize", handleResize); return () => { window.removeEventListener("resize", handleResize); }; }, []); The function returned inside useEffect runs: Before the next effect runs When the component unmounts Small detail. Big difference in performance. React is simple — until you understand the details. #ReactJS #FrontendDeveloper #JavaScript #WebDevelopment #LearningInPublic #100DaysOfCode
To view or add a comment, sign in
-
😅 When a JavaScript developer discovers React for the first time… At first: “Wait… HTML inside JavaScript???” 🤯 Then: “What is JSX?” “Why is everything a component?” “What is this useState thing?” After a few days: “Ohhhh… this is actually powerful.” With React, you stop thinking in pages… and start thinking in components. Instead of rewriting the whole DOM, you update only what changes. That’s when it clicks 💡 From: • Manipulating elements manually To: • Building reusable UI blocks • Managing state • Creating scalable frontend apps The confusion is normal. The growth is worth it. 💬 What confused you most when you first learned React? 📌 Save this if you're on your frontend journey #JavaScript #ReactJS #FrontendDevelopment #WebDevelopment #CodingJourney
To view or add a comment, sign in
-
💡JavaScript Tip💡 Lodash is the most popular utility library, but most developers make a mistake while using it. Instead of importing the entire library like this: import _ from 'lodash'; Always import only the functions that you're using in your code like this: import isEmpty from 'lodash/isEmpty'; As lodash is a heavy library, using only the required functions will reduce your final application bundle size a lot, as you can see in the image of this post. When using direct functions, only 6.3kb of lodash code is added, whereas using entire library, 71.5kb of code is added into your application. You can install the import cost VSCode extension to see that import size yourself. 𝗙𝗼𝗿 𝗺𝗼𝗿𝗲 𝘀𝘂𝗰𝗵 𝘂𝘀𝗲𝗳𝘂𝗹 𝗰𝗼𝗻𝘁𝗲𝗻𝘁, 𝗱𝗼𝗻'𝘁 𝗳𝗼𝗿𝗴𝗲𝘁 𝘁𝗼 𝗳𝗼𝗹𝗹𝗼𝘄 𝗺𝗲. #javascript #reactjs #nextjs #webdevelopment
To view or add a comment, sign in
-
Explore related topics
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