I wasted 6 hours debugging why my React component was slow. The component had 50 lines of clean code. But it re-rendered 400 times instead of 10. The culprit? A function created inside render. Here's the bug: ```jsx // BUG: Re-renders 400 times unnecessarily function ProjectCard({ project, onLike }) { const handleLike = () => { onLike(project.id) } return ( <div> <h3>{project.name}</h3> <button onClick={handleLike}>Like</button> // NEW function every render </div> ) } ``` Every time ProjectCard renders: - New `handleLike` function created - Child components see it as "changed" - Child components re-render - 400 parent renders = 400 child re-renders The fix: ```jsx import { useCallback } from 'react' function ProjectCard({ project, onLike }) { // handleLike stays the same reference across renders const handleLike = useCallback(() => { onLike(project.id) }, [project.id, onLike]) // Only recreate if dependencies change return ( <div> <h3>{project.name}</h3> <button onClick={handleLike}>Like</button> // Same function instance </div> ) } ``` Now: - `handleLike` reference stays same - Child components don't re-render unnecessarily - 400 renders → 40 renders (10x improvement) **The Pattern I Use:** Rule of thumb for my TypeScript+React projects: - Function passed to child = use useCallback - Computed value passed to child = use useMemo - Everything else = let React handle it **Real example from my portfolio:** In SphereMeet, the user list component was re-rendering 200 times/sec: ```jsx // BEFORE (slow) <UserList users={users} onSelect={(user) => updateSelected(user)} // NEW FUNCTION EVERY RENDER /> // AFTER (fast) const handleUserSelect = useCallback( (user) => updateSelected(user), [] ) <UserList users={users} onSelect={handleUserSelect} /> ``` Performance: 200 re-renders/sec → 2 re-renders/sec (100x!) **When NOT to use useCallback:** ❌ Don't use if: - Function is simple (1 line) - Not passed to child components - Child uses React.memo anyway - Dependency array is longer than function useCallback adds overhead. Only use when necessary. **The Lesson:** Most React performance issues are from: 1. Functions created in render 2. Objects created in render 3. Arrays created in render Fix those three, and React is blazingly fast. Comment "CALLBACK" + like + follow I'll send: → useCallback vs useMemo decision tree → When to use React.memo (and when NOT to) → Profiling tools to find re-render culprits → My real project examples (SphereMeet, Portfolio) (Must be following)
React Performance: useCallback to Avoid Unnecessary Rerenders
More Relevant Posts
-
I’ve been go through React hooks lately, and I just finished building a fully functional Todo List that handles complex state updates. 💻 I know this isn't a "polished" UI yet, but through building this project, I’ve learned an immense amount—from the hair-pulling bugs I faced to the satisfaction of finally making the logic work. While a Todo list is a classic "beginner" project, the real architectural lessons happened under the hood: 🔹 Immutability with the Spread Operator: Learning why we never mutate state directly and instead use [...prevTodos] to create clean, predictable UI updates. 🔹 Unique Identifiers: Implementing uuidv4 for keys to ensure React's reconciliation process stays efficient and bug-free. 🔹 Functional State Updates: Using the callback pattern (prevTodos) => ... to ensure I'm always working with the most recent data, avoiding "stale state" traps. 🔹 Conditional Styling: Using ternary operators to toggle text-decoration for a "Mark as Done" feature. Every bug I fixed was a lesson in disguise. Next step: persisting this data with localStorage and then focusing on the CSS! 🏗️ #ReactJS #FrontendDevelopment #Coding #WebDev #StateManagement #LearningByDoing
To view or add a comment, sign in
-
Using index as a key is dangerous Every React developer has written this at least once. items.map((item, index) => ( <li key={index}>{item}</li> )) Looks fine. Works fine. But it isn't This is Post 5 of the series: 𝗥𝗲𝗮𝗰𝘁 𝗨𝗻𝗱𝗲𝗿 𝘁𝗵𝗲 𝗛𝗼𝗼𝗱 Where I explain what React is actually doing behind the scenes. Here's what actually happens when you use index as key: You delete one item from a list. React doesn't know which item was removed. It just looks at positions. So it re-renders everything from that index downward. Input states get mismatched. Animations break. Bugs appear that you can't even reproduce consistently. And... No error. Just... wrong behavior. 🔑 Here's what React actually needs: A key isn't just something unique. It needs to be stable, unique, AND tied to the data — not the position. ❌ key={index} → breaks on delete, sort, filter ❌ key={Math.random()} → new key every render = React destroys and recreates the node ✅ key={item.id} → stable, reliable, React knows exactly who is who The rule is simple: If your list can ever be reordered, filtered, or deleted from... index as key will silently break your UI. Use your data's ID. If it doesn't have one, generate it at creation — not during render. const newItem = { id: crypto.randomUUID(), name: "New Task" } One tiny prop. Massive impact on how React tracks your entire list. In Post 6 of React Under the Hood: What Happens When You Call setState Follow Farhaan Shaikh if you want to understand react more deeply. 👉 Read the previous post - Understanding diffing algorithm: https://lnkd.in/dzW3NP_V #SoftwareEngineering #ReactJS #WebDevelopment #JavaScript #FrontendDevelopment #BuildInPublic #LearnInPublic #ReactUnderTheHood
To view or add a comment, sign in
-
New article from my Signals series. How do you integrate Signals into Vue without breaking your reactive model? This article walks through a minimal adapter that: - keeps dependency tracking inside your own reactive graph - avoids Vue double tracking - prevents scheduler conflicts and lifecycle issues If you're building framework-agnostic reactivity, this is a pattern you can reuse. #Vue #ref #Javascript #Typescript #Signal #WebDevelopment #Frontend #framework #Reactive #SystemDesign
To view or add a comment, sign in
-
After building a personal journal app with React 18, Tailwind CSS, and a Node/Express backend, I ran it through a full code audit. The result was a masterclass in the gaps between "it works" and "it's production-ready." Here's what came up: BUG FIXES → apiFetch was crashing on non-JSON error responses (502/504 HTML pages). Added a try/catch around res.json() with a readable fallback message. → The date formatter was silently producing "Invalid Date" for null/undefined values. Now returns '—'. → Math.random() IDs were used throughout. Swapped to crypto.randomUUID() for collision-safe IDs. → A useEffect in Toast was missing onDone in its dependency array — a subtle stale closure bug. → API responses were trusted to always be arrays. They're not. Array.isArray() guards added everywhere. ERROR HANDLING → Every save/delete was fire-and-forget. Wrapped in try/catch with inline user-visible errors. → Deletes had no confirmation dialog. One misclick = permanent data loss. → If the initial data load failed, the app rendered silently empty. Now shows a proper error screen. → Added a cancelled flag in useEffect to prevent state updates on unmounted components. CODE QUALITY → Extracted a useJournalData() custom hook to keep App lean. → Created reusable <FormError /> and <SaveButton /> components — the same pattern was copy-pasted 4 times. → BLANK_ENTRY/POST/PLACE were constants sharing a reference. Made them factory functions so each form gets a fresh object. → Replaced repeated new Date().toISOString().slice(0,10) with a todayISO() helper. PERFORMANCE → Filtered and sorted lists were recalculated on every render. Wrapped in useMemo. → Event callbacks recreated on every render. Wrapped in useCallback. ACCESSIBILITY → Clickable cards had no keyboard support. Added role="button", tabIndex, and onKeyDown Enter handlers. → Inputs were missing htmlFor/id associations and autoComplete attributes. → Decorative emoji lacked aria-hidden="true". The app "worked" before. Now it's resilient. The gap between working code and production code isn't about features — it's about what happens when things go wrong. Github repo : https://lnkd.in/dPz6Wqp7 #React #WebDevelopment #CodeQuality #JavaScript #FrontendDevelopment
To view or add a comment, sign in
-
🚀 Strengthening My Vue 3 Fundamentals Through Real-World Implementation Today I spent time deepening my understanding of a few core Vue 3 concepts that play a key role in building scalable and maintainable applications: 🔹 toRef() – Preserves reactivity when passing props into composables, ensuring consistent state updates 🔹 defineAsyncComponent() – Enables lazy loading of components, improving performance and reducing initial bundle size 🔹 getCurrentInstance() – Provides access to global properties (like $helper, $auth) within the Composition API While implementing these, I also gained clearer insight into Vue’s data flow architecture: ➡ Parent → Child communication using props ➡ Business logic abstraction using composables ➡ Child → Parent communication using emits This understanding helped me refactor code into a more modular, reusable, and maintainable structure. Continuing to focus on writing cleaner and more efficient frontend code. #VueJS #FrontendDevelopment #JavaScript #WebDevelopment #CleanCode #LearningInPublic
To view or add a comment, sign in
-
🚀 Day 8 / 21 — Frontend Challenge Today I built: 👉 Notes App (with Local Storage) 📝 🧠 Flow I designed before coding: Created UI layout for adding and displaying notes Designed input field + add button structure Captured user input using JavaScript Stored notes in browser using localStorage Displayed saved notes dynamically on screen Added delete functionality for each note Synced UI with localStorage on every update Loaded saved notes automatically on page refresh 🛠 Tech Used: HTML | CSS | JavaScript ✨ Features: • Add and delete notes easily • Data stored in localStorage (no backend) • Notes persist even after page refresh • Clean and responsive UI • Instant UI updates ⚡ Challenges Faced: Managing data sync between UI and localStorage was tricky. Ensuring notes don’t duplicate and update correctly after deletion required proper array handling. 💡 Key Learning: Learned how to use localStorage effectively, manage data using arrays, and dynamically update UI using DOM manipulation. 🙏 Guidance by: @Keyur Gohil 📚 Learning at: Red & White Multimedia Education 🎓 📌 GitHub Repo: https://lnkd.in/djcJvcad #21DaysChallenge #JavaScript #FrontendDevelopment #BuildInPublic #WebDevelopment #100DaysOfCode #LocalStorage
To view or add a comment, sign in
-
> **Stop guessing where your files go. Here's the React folder structure every developer needs to know. 🗂️** > > After years of messy codebases, late-night debugging sessions, and onboarding nightmares — the secret to a scalable frontend isn't just your code. It's **how you organize it.** > > Here's what each folder does and why it matters: > 📡 **API** — All your backend connections in one place. No more hunting for fetch calls. > 🎨 **Assets** — Static files, images, fonts. Clean and centralized. > 🧩 **Components** — Reusable UI building blocks. Write once, use everywhere. > 🌐 **Context** — Global state without prop drilling chaos. > 📦 **Data** — Static JSON content and constants. > 🪝 **Hooks** — Custom logic extracted and reusable across the entire app. > 📄 **Pages** — One folder per route. Clean, readable, scalable. > 🔄 **Redux** — Advanced state management for complex apps. > ⚙️ **Services** — Business logic and frontend services, separated from UI. > 🛠️ **Utils** — Helper functions that every file in your app will thank you for. > > A well-structured project isn't a luxury — **it's what separates junior from senior developers.** > > Save this. Share it with your team. Your future self will thank you. 💾 > > --- > 💬 What does YOUR folder structure look like? Drop it in the comments 👇 --- `#ReactJS` `#FrontendDevelopment` `#WebDevelopment` `#JavaScript` `#CleanCode` `#SoftwareEngineering` `#Programming` `#React` `#CodeNewbie` `#100DaysOfCode` `#FolderStructure` `#TechTips` `#DeveloperLife` `#SoftwareDeveloper` `#LearnToCode` `#OpenSource` `#CodingTips` `#FullStackDeveloper` `#FrontendEngineer` `#UIUXDevelopment` --- **Why this will go viral:** - Opens with a **pain point** every developer feels - Uses **emojis** for scanability on mobile - Ends with a **call to action** (comment + share) that boosts LinkedIn's algorithm - Mix of **broad** (`#WebDevelopment`) and **niche** (`#FolderStructure`) hashtags for maximum reach
To view or add a comment, sign in
-
-
> **Stop guessing where your files go. Here's the React folder structure every developer needs to know. 🗂️** > > After years of messy codebases, late-night debugging sessions, and onboarding nightmares — the secret to a scalable frontend isn't just your code. It's **how you organize it.** > > Here's what each folder does and why it matters: > 📡 **API** — All your backend connections in one place. No more hunting for fetch calls. > 🎨 **Assets** — Static files, images, fonts. Clean and centralized. > 🧩 **Components** — Reusable UI building blocks. Write once, use everywhere. > 🌐 **Context** — Global state without prop drilling chaos. > 📦 **Data** — Static JSON content and constants. > 🪝 **Hooks** — Custom logic extracted and reusable across the entire app. > 📄 **Pages** — One folder per route. Clean, readable, scalable. > 🔄 **Redux** — Advanced state management for complex apps. > ⚙️ **Services** — Business logic and frontend services, separated from UI. > 🛠️ **Utils** — Helper functions that every file in your app will thank you for. > > A well-structured project isn't a luxury — **it's what separates junior from senior developers.** > > Save this. Share it with your team. Your future self will thank you. 💾 > > --- > 💬 What does YOUR folder structure look like? Drop it in the comments 👇 --- **🔥 Hashtags:** `#ReactJS` `#FrontendDevelopment` `#WebDevelopment` `#JavaScript` `#CleanCode` `#SoftwareEngineering` `#Programming` `#React` `#CodeNewbie` `#100DaysOfCode` `#FolderStructure` `#TechTips` `#DeveloperLife` `#SoftwareDeveloper` `#LearnToCode` `#OpenSource` `#CodingTips` `#FullStackDeveloper` `#FrontendEngineer` `#UIUXDevelopment` --- **Why this will go viral:** - Opens with a **pain point** every developer feels - Uses **emojis** for scanability on mobile - Ends with a **call to action** (comment + share) that boosts LinkedIn's algorithm - Mix of **broad** (`#WebDevelopment`) and **niche** (`#FolderStructure`) hashtags for maximum reach
To view or add a comment, sign in
-
-
Hook: We need to talk about the awkward phase between useState and installing Redux. For a long time, I defaulted to useState for literally everything. Then you hit a feature—like a complex multi-step form or a data-heavy dashboard—and suddenly your component has six different state setters. Your event handlers turn into a tangled mess of setLoading(false), setData(res), and setError(null), all firing at once and risking race conditions. That’s exactly when useReducer goes from being "that confusing React hook" to the most vital tool for clean architecture. ✅ When you SHOULD use it: Dependent State: When updating one piece of state requires changing another at the exact same time (e.g., resolving an API call updates loading, data, and error simultaneously). Complex Objects: When your state is a deeply nested object or array that requires precise mapping or filtering on every update. Centralizing Logic: When you want to pull messy update logic out of your UI component and into a pure, highly testable JavaScript function. You can unit-test a reducer without ever touching a React component. ❌ When you SHOULD NOT use it: Simple Primitives: Please don't write a 15-line reducer with action types and switch statements just to toggle a modal open and closed. useState is perfectly fine for isolated, flat values. Just to look "advanced": The boilerplate is real. If the state is simple, keep the code simple. Don't frustrate the next developer who reads your code just to flex a hook. 💡 Why it matters in production: At the product-company level, you don't always need Redux, Zustand, or MobX for every feature. Pairing useReducer with the Context API gives you a powerful, localized global state. You can pass the dispatch function down the tree, completely avoiding prop-drilling without bloating your bundle size with third-party dependencies. It takes a minute to shift your brain from "updating values" to "dispatching actions," but your future self (and your teammates) will thank you when debugging. What is your personal threshold for making the switch from useState to useReducer? Let's debate below. #ReactJS #FrontendEngineering #SoftwareArchitecture #CleanCode #JavaScript
To view or add a comment, sign in
-
More from this author
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