🚀 React Series Part 10: Custom Hooks - Reuse Logic Like a Pro So far, we’ve used built-in hooks like useState, useEffect, useMemo. But what if you want to reuse logic across components? 🤔 👉 That’s where Custom Hooks come in 💡 💡 What are Custom Hooks? Custom Hooks are just JavaScript functions that use React hooks internally. 📌 Rule: 👉 Must start with use (naming convention) 🔥 Why do we need them? Imagine writing the same logic in multiple components: • API calls • Form handling • Event listeners ❌ Leads to duplication ❌ Hard to maintain ✅ Custom Hooks solve this 🔧 Example: Reusable Counter Logic function useCounter(initialValue = 0) { const [count, setCount] = useState(initialValue); const increment = () => setCount(c => c + 1); const decrement = () => setCount(c => c - 1); return { count, increment, decrement }; } 👉 Using it in a component: const { count, increment, decrement } = useCounter(); 💡 Real-world Example: API Fetching function useFetch(url) { const [data, setData] = useState(null); useEffect(() => { fetch(url) .then(res => res.json()) .then(setData); }, [url]); return data; } 👉 Now reusable across components 🚀 🔁 What’s happening internally? • Each component gets its own isolated state • Logic is shared, not the data • Cleaner and more modular code ⚠️ Best Practices ✔ Keep hooks focused (single responsibility) ✔ Avoid too much abstraction ✔ Handle loading/error states in real apps 🧠 Simple takeaway Custom Hooks = Reusable logic 🧩 Components = UI layer 🎨 Let’s keep going 🚀 #ReactJS #Learning #frontendDev
Custom Hooks for Reusable Logic in React
More Relevant Posts
-
I built a real User Management System from scratch Most developers start with tutorials… I decided to turn knowledge into a real working project. I just built a fully functional User Management Dashboard using vanilla JavaScript. 🔹 What it does: ✔ Fetches real user data from an API ✔ Lets you add new users dynamically ✔ Search users in real time ✔ Delete users instantly ✔ Stores data using Local Storage 🔹 Tech Stack: HTML • CSS • JavaScript • API Integration What I learned from this project is not just coding… but how real systems handle data, interaction, and user experience. 💡 Still improving, still building… one project at a time. 🔗 GitHub: https://lnkd.in/dJZjgYsp I’d appreciate any feedback or suggestions 🙌 #WebDevelopment #Frontend #JavaScript #CodingJourney #BuildInPublic
To view or add a comment, sign in
-
-
hi connections Day 28 of 30: Building a Custom EventEmitter with LeetCode 2694 🚀 Today’s challenge was a deep dive into the Observer Pattern by building a functional EventEmitter. This is the secret sauce behind how clicks work in the browser and how Node.js handles asynchronous operations. The Concept An EventEmitter allows different parts of an application to talk to each other without being "hard-wired" together. One part of your code subscribes to an event (waits for a signal), and another part emits that event (sends the signal). The Implementation Logic: The Registry: I used a Map to store event names as keys and arrays of callback functions as values. The Subscription: When a user subscribes, we add their function to the list and return a custom unsubscribe method. Thanks to closures, the unsubscribe function "remembers" exactly which callback to remove later. The Trigger (Emit): When an event is emitted, we find the list of functions for that event name and execute each one, passing along any data as arguments. Why It’s Crucial for MERN Developers Understanding event-driven architecture is essential for: ✅ React: Handling complex state updates or custom hooks. ✅ Node.js: Working with streams, servers, and the built-in events module. ✅ Real-time Apps: Managing socket connections for chat apps or live notifications. By decoupling our code this way, we make it more modular, easier to test, and much more scalable. Only 2 days left! The final stretch is here. 💻✨ #JavaScript #LeetCode
To view or add a comment, sign in
-
-
Raw JSON is messy. I created something to fix it. I deployed my first project: the Universal API Engine. It’s a client-side tool that takes disorganized endpoint data and quickly turns it into a clear, searchable interface. Live Demo: https://lnkd.in/gRUV8HBj Source Code : https://lnkd.in/giuVkPvs I wanted to fully understand the DOM and network requests. So, I built this with no dependencies. It’s all in pure HTML5, CSS3, and Vanilla JavaScript. What it handles right now (v1.0): - Deep-value filtering (searches every nested object, not just top-level). - Interactive nested data exploration. - Persistent session history via LocalStorage. - Fully responsive layout with a custom dark/light theme. What’s next: Currently, it only processes textual JSON. The v2.0 roadmap includes support for multiple formats to handle raw binary data, meaning it will display images, audio, and video directly from the endpoints. Since this is my first deployment, I know the code has some flaws. There are definitely UI/UX issues hiding in there. I want to stress test this tool. Try it out, throw a huge JSON endpoint at it, and let me know where it breaks. I’m looking for honest feedback, bug reports, and tips on how to improve it. #VanillaJS #WebDevelopment #Frontend #Engineering #APIs #ChaiAurCohort #ChaiAurCode #chaiaurcode #learninginpublic
To view or add a comment, sign in
-
𝗥𝗲𝗮𝗰𝘁 𝟮𝟬𝟮𝟲 𝗟𝗲𝗮𝗿𝗻𝗶𝗻𝗴 𝗥𝗼𝗮𝗱𝗺𝗮𝗽 You want to learn React in 2026. The ecosystem moves fast. You need a plan. Focus on skills jobs want. Start with basics. - Components, props, and state. - Re-renders and reconciliation. - Stable keys for lists. - Controlled and uncontrolled forms. - Hooks: useState, useEffect, useMemo, useCallback, useRef, useContext. - Learn data flow and side effects. Learn TypeScript. - Type your props. - Type your component returns. - Use union types for UI states. - Type your API responses. Set up your tools. - Use ESLint and Prettier. - Use React Testing Library and Vitest. - Use Playwright for end-to-end tests. - Test user outcomes. Manage your state. - Separate server state from client state. - Use TanStack Query for server state. - Use local state and context for client state. - Use Zustand or Redux Toolkit for complex global state. Go beyond the library. - Learn Next.js. - Study routing and server components. - Use React DevTools Profiler to fix speed. - Learn accessibility. - Use React Hook Form. Follow this 10-week plan. - Weeks 1-2: Fundamentals and hooks. - Weeks 3-4: TypeScript and testing. - Weeks 5-6: Data fetching and auth. - Weeks 7-8: Next.js and deployment. - Weeks 9-10: Accessibility and performance. Build these projects. - Admin dashboard with filters. - Content app with search. - E-commerce cart and checkout. Build apps a real team would maintain. Source: https://lnkd.in/g9JdYu29
To view or add a comment, sign in
-
𝗧𝗵𝗶𝘀 𝗜𝘀 𝗪𝗵𝘆 𝗜 𝗕𝗎𝗶𝗹𝘁 𝗠𝘆 𝗘𝗥𝗣 𝗦𝘆𝘀𝘁𝗲𝗺 𝗨𝘀𝗶𝗻𝗴 𝗩𝗮𝗻𝗶𝗹𝗹𝗮 𝗝𝗮𝗙𝗮𝘀𝗰𝗿𝗶𝗽𝘁 When I share my journey building an ERP system, other devs often ask: "What framework did you use?" I used to start building with Svelte, React, or Next.js, but I felt restricted. Now, JavaScript has grown up. You can build reusable components, use ES module imports, write clean arrow functions, and structure things in an object-oriented way without a framework. Here are a few reasons why I chose vanilla JavaScript: - I can build things exactly the way I want - I use classes as entry points for each page, keeping everything else in exportable modules - I follow a repeatable pattern: constructor, init, html, render, listeners - I use universal components like Locale, Session, Header, and Footer shared across the whole system I skip types and use simple variables and objects. This works for a solo-built system, but I would not recommend it to a larger team. I like JavaScript because it runs natively in the browser. I can fetch everything needed for full UI rendering and localization in one shot. My Lighthouse scores are high, with most pages hitting 100% without optimization. I also avoid dependencies, which can cause problems when updating packages. My project is cleaner, and I can make changes directly without recompiling anything. I want to build an environment where AI agents can navigate the codebase and make changes based on user feedback. I use a single JS call for data fetching, and I treat each section of the UI as its own isolated thing. I learned that declaring listeners directly in the HTML is a good solution to avoid problems with partial DOM updates. Source: https://lnkd.in/gQJAS-Kc
To view or add a comment, sign in
-
𝗧𝗵𝗶𝘀 𝗜𝘀 𝗪𝗵𝘆 𝗜 𝗕𝗎𝗶𝗹𝘁 𝗠𝘆 𝗘𝗥𝗣 𝗦𝘆𝘀𝘁𝗲𝗺 𝗨𝘀𝗶𝗻𝗴 𝗩𝗮𝗻𝗶𝗹𝗹𝗮 𝗝𝗮𝗙𝗮𝘀𝗰𝗿𝗶𝗽𝘁 When I share my journey building an ERP system, other devs often ask: "What framework did you use?" I used to start building with Svelte, React, or Next.js, but I felt restricted. Now, JavaScript has grown up. You can build reusable components, use ES module imports, write clean arrow functions, and structure things in an object-oriented way without a framework. Here are a few reasons why I chose vanilla JavaScript: - I can build things exactly the way I want - I use classes as entry points for each page, keeping everything else in exportable modules - I follow a repeatable pattern: constructor, init, html, render, listeners - I use universal components like Locale, Session, Header, and Footer shared across the whole system I skip types and use simple variables and objects. This works for a solo-built system, but I would not recommend it to a larger team. I like JavaScript because it runs natively in the browser. I can fetch everything needed for full UI rendering and localization in one shot. My Lighthouse scores are high, with most pages hitting 100% without optimization. I also avoid dependencies, which can cause problems when updating packages. My project is cleaner, and I can make changes directly without recompiling anything. I want to build an environment where AI agents can navigate the codebase and make changes based on user feedback. I use a single JS call for data fetching, and I treat each section of the UI as its own isolated thing. I learned that declaring listeners directly in the HTML is a good solution to avoid problems with partial DOM updates. Source: https://lnkd.in/gQJAS-Kc
To view or add a comment, sign in
-
You’re still building forms manually from JSON? --- Every time I get a JSON response, I end up doing the same thing: → read structure → map fields → wire inputs → repeat… again --- It’s boring. It’s repetitive. And it shouldn’t exist in 2026. --- So I built something for myself: 👉 Paste JSON 👉 Get a working form instantly --- No setup. No backend. No config headaches. Just: JSON → UI --- Introducing: 🔧 JSON → Form (part of useSignal) 👉 https://lnkd.in/grSx-SEi --- It’s fully browser-native. Which means: - your data never leaves your machine - everything runs instantly - no dependency on any service --- This isn’t just a generator. It’s a way to: → skip repetitive UI work → prototype faster → actually focus on logic --- Try it once. You probably won’t go back to building forms manually. --- 💬 Curious — how are you handling JSON → forms today? #frontend #webdevelopment #javascript #reactjs #devtools #buildinpublic #productivity #developers #webdev
To view or add a comment, sign in
-
-
74% of developers still default to client-side rendering with Next.js 15. But should they? Next.js 15 has introduced server components, a significant shift in how we think about rendering and state management. Are we witnessing the twilight of client-side rendering, or is this just another tool in our developer toolkit? From my experience, server components are a game-changer for performance. They allow us to offload work to the server, minimizing the client’s load, which can drastically improve page load times. However, it's not a silver bullet. Server components come with challenges, like figuring out how to manage state and how to optimize server resources effectively. Here's a small TypeScript snippet to illustrate how you can fetch data within a server component: ```typescript import { fetch } from 'next/server'; async function ServerComponent() { const data = await fetch('/api/data'); return ( <div> <h1>Data from Server</h1> <pre>{JSON.stringify(data, null, 2)}</pre> </div> ); } ``` I recently used AI-assisted development to prototype server components quickly. It’s incredible how AI coding tools can speed up development, allowing me to focus on optimizing and refining. So, are we looking at a future where client-side rendering is obsolete, or will it continue to play a critical role in our apps? Have you tried server components yet? How do you see them fitting into your development workflow? #WebDevelopment #TypeScript #Frontend #JavaScript
To view or add a comment, sign in
-
-
🚀 From Idea to Interface—Progress You Can See. #Day2 of building DataVault—and today’s milestone feels real. Alhamdulillah, I’ve successfully converted the entire UI into working code using React and Tailwind CSS. What started as a concept is now a fully functional front-end with a working dashboard. 💻 What’s done: • Complete UI implementation using React + Tailwind CSS • Clean, responsive design now fully interactive • Dashboard functionality is up and running smoothly This is a big step—because now DataVault isn’t just an idea or a design… it’s something you can actually use. 🔐 What’s next: My next focus is implementing authentication to make the platform secure and accessible for real users. The goal is to ensure anyone can safely use DataVault to manage their data with confidence. ⏳ The 7-Day Challenge continues… I’m confident that within the next 2 days, this will evolve into a fully working application. 🤝 I’d love your input: If you have suggestions, features you’d like to see, or feedback—please share. Your insights can help shape this into something truly valuable. Let’s keep building in public. Day 7 is getting closer. 🚀 #BuildInPublic #WebDevelopment #ArtificialIntelligence #SaaS #ReactJS #TailwindCSS #JWT #DataSecurity #Developers #TechJourney #NodeJS #Typescrit #JavaScript #vercel #framermotion
To view or add a comment, sign in
-
💡 Most Developers Don’t Understand Async Properly (And It Shows 👀) Let’s be brutally honest. Most developers use async/await… But when things break --- they have no idea why. We write: await fetchData(); And feel like: “Haan bhai, async likh diya… ab sab sorted hai 😎” Until production says: “bhai kuch bhi sorted nahi hai 💀” The bug was in their async flow. → They stacked awaits without understanding the execution order → They ignored the event loop → They guessed instead of reasoning Here is the truth. Async is not syntax. Async is execution. You write await fetchData() and feel in control. The engine is doing something very different. JavaScript runs on a single thread. It uses the call stack. It offloads work to Web APIs. It schedules callbacks in queues. Then the event loop decides what runs next. Microtasks run before macrotasks. Always... Look at this. console.log("Start"); setTimeout(() => console.log("Timeout"), 0); Promise.resolve().then(() => console.log("Promise")); console.log("End"); Most developers guess wrong. Actual output is clear. "Start" -> "End" -> "Promise" -> "Timeout" No randomness. No magic. Just rules. Because: -> JS doesn’t care about your intuition -> It follows the event loop strictly If you do not know these rules, you are guessing. And guessing breaks systems. 🔥 Why This Matters If you don’t understand async: -> You cannot debug race conditions -> You cannot explain failures -> You cannot scale your thinking The language is not confusing. Your mental model is incomplete. Fix that. Start predicting execution before running code. Trace the stack. Track the queue. Respect the event loop. Pro Tip... Use Chrome DevTools to debug and step through async code That is how real developers work. Syntax is the entry. Understanding execution is the skill. #JavaScript #AsyncAwait #EventLoop #WebDevelopment #SoftwareEngineering
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