I was repeating the same logic in every component… and it started getting messy 😅 Yes, seriously. For a long time, I was doing this in React: useEffect(() => { fetchData(); }, []); const [data, setData] = useState(); const [loading, setLoading] = useState(false); Same pattern… in multiple components ❌ ⚠️ This caused: • Code duplication • Hard-to-maintain components • Bigger, messy files 💡 Then I changed my approach: Instead of repeating logic everywhere, 👉 I created a custom hook 🧠 Example: useFetch(url) Handles: • API call • Loading state • Error handling ✅ Result: • Cleaner components • Reusable logic • Easier maintenance 🔥 What I learned: If you’re repeating the same logic… you’re probably missing a custom hook. #ReactJS #FrontendDeveloper #JavaScript #CodingTips #WebDevelopment
Create a Custom Hook for Reusable Logic in React
More Relevant Posts
-
JavaScript Closures are confusing… until they’re not ⚡ Most developers memorize the definition but struggle to actually understand it. Let’s simplify it 👇 💡 What is a closure? A closure is when a function 👉 remembers variables from its outer scope even after that scope is finished 🧠 Example: function outer() { let count = 0; return function inner() { count++; console.log(count); }; } const fn = outer(); fn(); // 1 fn(); // 2 fn(); // 3 ⚡ Why this works: inner() still has access to count even after outer() has executed 🔥 Where closures are used: • Data hiding • State management • Event handlers • Custom hooks in React #JavaScript #FrontendDeveloper #ReactJS #CodingTips #WebDevelopment
To view or add a comment, sign in
-
Why is my code running "out of order"? (Eager vs. Lazy Evaluation) Ever passed a function as an argument and wondered why it executed before the function it was passed into? Look at this common "gotcha": javascript const main = (fn) => { console.log("start"); fn(); console.log("end"); }; const createLogger = (msg) => { console.log("start logger"); return () => console.log(msg); }; // ❌ Unexpected Order: "start logger" -> "start" -> "success" -> "end" main(createLogger("success")); Use code with caution. What’s happening? This is Eager Evaluation. In JavaScript, arguments are evaluated immediately before the outer function runs. Because we used parentheses () on createLogger, JS executes it first to find out what value to give to main. It’s like cooking a 5-course meal before your guests even knock on the door! 🥘 The Fix: Lazy Evaluation 💤 If we want main to control the timing, we need to wrap our logic in a "thunk" (a wrapper function). This tells JS: "Don't run this yet; run it only when I call it." javascript // ✅ Correct Order: "start" -> "start logger" -> "success" -> "end" main(() => createLogger("success")()); Use code with caution. Why does this matter in Node.js? Understanding this distinction is huge for: ✅ Middleware: Deciding when a request starts/ends. ✅ Performance: Avoiding expensive calculations unless they are actually needed. ✅ Closures: Controlling scope and execution timing. Stop executing, start referencing! 🚀 #JavaScript #WebDevelopment #NodeJS #CodingTips #SoftwareEngineering
To view or add a comment, sign in
-
-
I spent months writing async Node.js code without really understanding it. Then a production bug taught me the event loop the hard way. Here's what you need to know: Node.js is single-threaded — but it handles thousands of concurrent requests without freezing. How? The event loop. It has 4 key parts: 1. Call Stack — Your sync code runs here, line by line. One thing at a time. 2. libuv Thread Pool — Async tasks (file I/O, HTTP requests) get offloaded here. Your code keeps running. 3. Microtask Queue — Promise callbacks live here. They run BEFORE anything else queued. 4. Macrotask Queue — setTimeout and setInterval callbacks wait here. This explains a classic JS gotcha: console.log('1') setTimeout(() => console.log('2'), 0) Promise.resolve().then(() => console.log('3')) console.log('4') Output: 1 → 4 → 3 → 2 The Promise fires before the setTimeout — even with a 0ms delay. Once you understand this, a whole category of async bugs just... disappears. What part of async JavaScript tripped you up most? Drop it below 👇 #NodeJS #JavaScript #WebDevelopment #SoftwareEngineering #FullStack
To view or add a comment, sign in
-
-
Everyone reads about ".call()", ".bind()", ".apply()" But the real confusion is: 👉 Where do we actually use them? A simple example from real code: const user = { name: "Jayhind" }; function greet() { console.log("Hello " + this.name); } Now imagine this function is reused somewhere else: const anotherUser = { name: "Rahul" }; greet.call(anotherUser); // Hello Rahul 👉 Here ".call()" helps us control "this" dynamically --- Now ".bind()": const greetRahul = greet.bind(anotherUser); greetRahul(); // Hello Rahul 👉 Useful when you want to store function with fixed context --- Real-world use case: class Service { constructor() { this.name = "API Service"; } log() { console.log(this.name); } } const service = new Service(); setTimeout(service.log, 1000); // undefined ❌ setTimeout(service.log.bind(service), 1000); // API Service ✅ 👉 This is where ".bind()" actually matters --- One simple way to remember: - ".call()" → run function immediately with context - ".apply()" → same as call, but args in array - ".bind()" → return new function with fixed context Most tutorials explain syntax. Real understanding comes from where it breaks. #JavaScript #NodeJS #CallBindApply #BackendDevelopment #JSConcepts
To view or add a comment, sign in
-
-
🧠 Day 26 — Rest vs Spread Operator in JavaScript (Simplified) Both use ... — but they do very different things 👀 --- 🔍 The Idea 👉 Spread → Expands values 👉 Rest → Collects values --- ⚡ 1. Spread Operator ... 👉 Expands elements const arr = [1, 2, 3]; const newArr = [...arr, 4]; console.log(newArr); // [1, 2, 3, 4] 👉 Also used in objects const user = { name: "John" }; const newUser = { ...user, age: 25 }; --- ⚡ 2. Rest Operator ... 👉 Collects remaining values function sum(...nums) { return nums.reduce((a, b) => a + b, 0); } sum(1, 2, 3); // 6 --- 🧠 Key Difference Spread → Expands data Rest → Gathers data --- ⚠️ Important Rule 👉 Rest must be last parameter function test(a, ...rest) {} // ✅ --- 🚀 Why it matters ✔ Cleaner code ✔ Flexible functions ✔ Used heavily in React & modern JS --- 💡 One-line takeaway: 👉 “Spread expands, Rest collects.” --- Once you understand this, working with arrays & functions becomes much easier. #JavaScript #ES6 #SpreadOperator #RestOperator #WebDevelopment #Frontend #100DaysOfCode 🚀
To view or add a comment, sign in
-
𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁 𝗺𝗼𝗱𝘂𝗹𝗲 𝗳𝗼𝗿𝗺𝗮𝘁𝘀 𝗰𝗮𝗻 𝗯𝗲 𝗰𝗼𝗻𝗳𝘂𝘀𝗶𝗻𝗴 — 𝗲𝘀𝗽𝗲𝗰𝗶𝗮𝗹𝗹𝘆 𝘄𝗵𝗲𝗻 𝘆𝗼𝘂 𝗿𝘂𝗻 𝗶𝗻𝘁𝗼 𝗱𝗶𝗳𝗳𝗲𝗿𝗲𝗻𝘁 𝗼𝗻𝗲𝘀 𝗮𝗰𝗿𝗼𝘀𝘀 𝗽𝗿𝗼𝗷𝗲𝗰𝘁𝘀. Here’s a quick mental model 👇 𝗖𝗼𝗺𝗺𝗼𝗻𝗝𝗦 Used in classic Node.js backends const lib = require('lib'); Simple and synchronous. Still widely used, but gradually being replaced. 𝗘𝗦 𝗠𝗼𝗱𝘂𝗹𝗲𝘀 (𝗘𝗦𝟮𝟬𝟭𝟱+) Modern standard for browsers and Node.js import lib from 'lib'; Tree-shakable, static, and the future of JavaScript. 𝗔𝗠𝗗 Designed for browsers before native modules existed (RequireJS era) define(['dep'], function(dep) { ... }); Now mostly legacy. SystemJS Dynamic module loader System.register([...], function(...) { ... }); Used in specific cases like plugin systems or legacy apps. 𝗨𝗠𝗗 "Write once, run anywhere" format Works in both browser and Node.js if (typeof define === 'function') { ... } Common in older libraries that needed maximum compatibility. 💡 Key takeaway: Use 𝗘𝗦 𝗠𝗼𝗱𝘂𝗹𝗲𝘀 for modern apps Expect 𝗖𝗼𝗺𝗺𝗼𝗻𝗝𝗦 in backend or legacy code Treat 𝗔𝗠𝗗 / 𝗦𝘆𝘀𝘁𝗲𝗺𝗝𝗦 / 𝗨𝗠𝗗 as historical or niche Understanding these formats makes debugging build issues much easier. #JavaScript #Frontend #WebDevelopment #NodeJS #SoftwareEngineering #DevTips #Programming
To view or add a comment, sign in
-
-
🚀 Web APIs Made Simple (With Quick Explanations) When I started learning JavaScript, I was confused about how API calls, UI updates, and storage actually work. Then I understood this 👇 👉 JavaScript alone is limited 👉 Browsers provide powerful features called Web APIs --- 💡 Simple idea: JavaScript = Brain 🧠 Web APIs = Tools + Internet 🌐 --- 🔥 Important Web APIs (with simple explanations): 1. Fetch API → Used to call backend APIs and get data 2. DOM API → Used to update and control HTML elements 3. LocalStorage API → Store data permanently in browser 4. SessionStorage API → Store data for one tab/session 5. Timer API → Run code after delay (setTimeout) or repeatedly (setInterval) 6. Geolocation API → Get user’s current location 7. Media API → Access camera and microphone 8. WebSocket API → Real-time communication (chat apps, live data) 9. Canvas API → Draw graphics, charts, games 10. Web Workers API → Run heavy tasks in background without blocking UI --- 💡 Reality: You don’t need all of them at once. Most apps mainly use: 👉 DOM 👉 Fetch 👉 Storage 👉 Events --- 📈 Best way to learn: Start building: - Todo App (DOM + Storage) - API App (Fetch) - Chat App (WebSocket) --- 🔥 Once you understand Web APIs, JavaScript becomes much more powerful. --- 💬 Which API was hardest for you to understand? --- 📚 Full article on Web APIs: https://lnkd.in/gHk3dyqz #javascript #webdevelopment #frontend #reactjs #programming #coding #100daysofcode
To view or add a comment, sign in
-
Stop writing React like it's 2021. 🛑 The ecosystem has evolved. If you want a cleaner, more performant codebase, it is time to upgrade your patterns: 🔄 Data Fetching: useEffect ❌ TanStack Query ✅ 🧠 Global State: Context API ❌ Zustand ✅ 📝 Forms: useState / useRef spam ❌ React Hook Form / React 19 Actions ✅ ⚡ Performance: useMemo / useCallback ❌ React Compiler ✅ 🎨 Styling: CSS-in-JS / bloated SCSS ❌ Tailwind CSS ✅ 🛡️ Validation: Manual checks & any ❌ Zod + TypeScript ✅ Less boilerplate. Fewer unnecessary re-renders. Better developer experience. What is a tool or pattern you finally stopped using this year? 👇 #ReactJS #WebDevelopment #Frontend #TypeScript #TailwindCSS
To view or add a comment, sign in
-
Most developers get this wrong 👇 Referential Constraints ≠ Key Constraints Referential Constraints → ensure relationships between tables stay valid 🔗 Key Constraints → ensure correctness and uniqueness within a table 🧩 When building real systems, you don’t just use Referential Constraints — you rely on Key Constraints to enforce data integrity at the row level, while Referential Constraints protect relationships across tables (like users ↔ orders). This small distinction changes how you design systems ⚡ especially when dealing with scaling, data consistency, and avoiding orphan records. Building systems > memorizing concepts 🚀 What’s one concept developers often misunderstand? 🤔 #fullstackdeveloper #softwareengineering #webdevelopment #javascript #reactjs #backend #buildinpublic
To view or add a comment, sign in
-
-
Your React component is leaking memory and you have no idea. I just read about this pattern in the docs. I realized I was fighting the React lifecycle for months 😅 The problem? Race conditions from uncleared async requests. When you fetch data on state change: - User changes profile 10 times in 1 minute - 10 API requests fire - Only the LAST response updates state - Previous 9 complete but state is already changed - Memory leak + stale data Most devs skip cleanup. Most tutorials show incomplete examples. Result? Wasted requests, stale data, memory leaks. #React #JavaScript #Performance #WebDevelopment
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