Day 22: Error Boundaries in React In real-world applications, errors can happen anytime. A single error in one component can crash the entire UI. To handle this properly, React provides: Error Boundaries 📌 What are Error Boundaries? Error Boundaries are React components that catch JavaScript errors in their child component tree and display a fallback UI instead of crashing the whole app. ✅ Prevents complete app crash ✅ Displays fallback UI ✅ Improves user experience 📌 What Error Boundaries can catch? ✔ Errors in rendering ✔ Errors in lifecycle methods ✔ Errors in constructors of child components 📌 What Error Boundaries cannot catch? ❌ Errors inside event handlers ❌ Errors in async code (setTimeout, promises) ❌ Errors in server-side rendering 📌 Example of an Error Boundary import React from "react"; class ErrorBoundary extends React.Component { constructor(props) { super(props); this.state = { hasError: false }; } static getDerivedStateFromError(error) { return { hasError: true }; } componentDidCatch(error, info) { console.log("Error:", error); console.log("Info:", info); } render() { if (this.state.hasError) { return <h2>Something went wrong!</h2>; } return this.props.children; } } export default ErrorBoundary; 📌 How to use it? import ErrorBoundary from "./ErrorBoundary"; import App from "./App"; function Main() { return ( <ErrorBoundary> <App /> </ErrorBoundary> ); } Now, if any child component crashes, the app will show: 👉 "Something went wrong!" 📌 Why Error Boundaries are important? 🔥 Used in production apps 🔥 Prevents blank screens 🔥 Helps debugging errors #ReactJS #ErrorBoundary #FrontendDevelopment #JavaScript #WebDevelopment #CodingJourney #LearnInPublic
React Error Boundaries: Prevent App Crashes and Improve UX
More Relevant Posts
-
🚀 Day 24/30 – Error Boundaries (Handle Crashes Gracefully) Everything works fine… until ONE component crashes your entire app 💥 And suddenly 👇 👉 White screen 👉 Angry users 👉 Debugging nightmare 😵 Today I learned how real-world React apps handle this ⚡ 👉 Error Boundaries --- 💻 The Problem: In React, if a component crashes ❌ 👉 The whole app can crash --- 💻 The Solution: 👉 Error Boundaries = Safety Net 🛡️ They catch errors and show fallback UI instead of breaking everything. --- 💻 Example: class ErrorBoundary extends React.Component { constructor(props) { super(props); this.state = { hasError: false }; } static getDerivedStateFromError() { return { hasError: true }; } componentDidCatch(error, info) { console.log(error, info); } render() { if (this.state.hasError) { return <h2>Something went wrong 😢</h2>; } return this.props.children; } } --- 💻 Usage: <ErrorBoundary> <Dashboard /> </ErrorBoundary>--- 🔥 What actually happens: ❌ Without Error Boundary → Whole app crashes ✅ With Error Boundary → Only broken component fails → Rest of app works smoothly --- 💡 Why this matters: - Better user experience - Prevents full app crash - Essential for production apps --- ⚡ Advanced Insight (Most people don’t know): Error Boundaries do NOT catch: ❌ API errors ❌ setTimeout errors ❌ Event handler errors 👉 You still need proper error handling there --- 🔥 Key Takeaway: Good developers fix bugs… 👉 Great developers prevent crashes --- Be honest 👇 If your app crashes today… will users see a fallback UI or a blank screen? 👀 #React #ErrorHandling #FrontendDevelopment #JavaScript #CleanCode
To view or add a comment, sign in
-
-
I improved a React app’s render performance by ~12%… by removing useMemo. ⚡ Yes — removing it. Most developers treat useMemo like a safety net: “Wrap it… just in case.” I used to do the same. That was the mistake. ❌ The problem // Memoizing a trivially cheap value const fullName = useMemo(() => { return `${firstName} ${lastName}`; }, [firstName, lastName]); Looks clean, right? But here’s what actually happens: - React stores the memoized value - Tracks dependencies - Compares them on every render For something as cheap as string concatenation… 👉 the overhead costs more than the computation. ✅ The fix // Just compute it inline — zero overhead const fullName = `${firstName} ${lastName}`; Use useMemo only when the computation is actually expensive: const sortedList = useMemo(() => { return items.sort((a, b) => b.score - a.score); }, [items]); 💡 Why this matters - No unnecessary memoization overhead - Cleaner, more readable code - Easier debugging & profiling - useMemo becomes a meaningful signal (not noise) 📊 Real impact In a component tree with 40+ memoized values, removing unnecessary useMemo calls reduced render time by ~12%. Sometimes, the best optimization is… 👉 removing the “optimization”. 🔍 I’ve seen this a lot in data-heavy dashboards and complex UI systems, where premature memoization quietly hurts performance instead of helping. 💬 What React optimization habit did you have to unlearn the hard way? #React #Frontend #WebPerformance #JavaScript #CleanCode #SoftwareEngineering
To view or add a comment, sign in
-
-
🚨 useState is not asynchronous… but it’s also not immediate. This subtle detail causes a lot of bugs in real-world React apps. Consider this 👇 const [count, setCount] = useState(0); const handleClick = () => { setCount(count + 1); setCount(count + 1); }; 👉 What do you expect the final value to be? Most developers say: 2 Actual result: 1 ❌ 💡 What’s happening under the hood? React batches state updates and schedules them for performance. Both updates use the same stale closure value of count (which is 0). So React processes: → setCount(0 + 1) → setCount(0 + 1) Final state = 1 🔥 Correct Approach (Functional Updates) setCount(prev => prev + 1); setCount(prev => prev + 1); Now React processes: → prev = 0 → 1 → prev = 1 → 2 ✅ ⚡ Why this matters in production This isn’t just a “beginner mistake”: It affects: 1. Complex forms with multiple updates 2. Async flows (API calls, debouncing) 3. State updates inside loops or callbacks 4. Concurrent rendering in modern React 🧠 Key Insight The problem isn’t “async vs sync” It’s how closures capture state at render time React doesn’t mutate state immediately— it schedules updates based on the render snapshot. 💭 Rule I follow: 👉 If next state depends on previous state → ALWAYS use functional updates. Have you debugged a stale state issue like this in production? Curious to know how you handled it 👇 #ReactJS #FrontendDevelopment #JavaScript #ReactHooks #PerformanceOptimization #SoftwareEngineering
To view or add a comment, sign in
-
-
🚨 JavaScript Memory Leaks — The Silent Performance Killer Ever had your app slow down over time… without any obvious reason? Chances are, you’re dealing with a memory leak. Let’s break it down 👇 🧠 What is a Memory Leak? A memory leak happens when your application keeps holding references to objects that are no longer needed, preventing JavaScript’s garbage collector from cleaning them up. Think of it like: 👉 Renting rooms in a hotel… but never checking out. ⸻ 🔥 Common Causes of Memory Leaks in JavaScript 1️⃣ Global Variables name = "Tanmay"; // Oops, accidentally global These stay in memory for the entire lifecycle of your app. ⸻ 2️⃣ Forgotten Timers & Intervals setInterval(() => { console.log("Running..."); }, 1000); If not cleared, they keep running forever. ⸻ 3️⃣ Detached DOM Elements let element = document.getElementById("btn"); document.body.removeChild(element); // Still referenced → not garbage collected ⸻ 4️⃣ Closures Holding References function outer() { let largeData = new Array(1000000).fill("🔥"); return function inner() { console.log("Still holding largeData"); }; } Closures can unintentionally “trap” memory. ⸻ 5️⃣ Event Listeners Not Removed window.addEventListener("resize", handleResize); If not removed, they stick around even when not needed. ⸻ ⚡ Why It Matters? • Slower performance 🐢 • Increased memory usage 📈 • Crashes in long-running apps 💥 ⸻ 🛠️ How to Prevent Memory Leaks ✔ Use let / const (avoid accidental globals) ✔ Clear timers → clearInterval, clearTimeout ✔ Remove event listeners when done ✔ Nullify unused references ✔ Use tools like Chrome DevTools → Memory tab ⸻ 💡 Pro Tip (Easy Memory Hook): 👉 “If something is STILL REFERENCED, it’s STILL IN MEMORY.” ⸻ As developers, we often optimize algorithms… But ignoring memory is like fixing speed on a car with a leaking fuel tank. 💬 Have you ever debugged a tricky memory leak? Share your story! #JavaScript #WebDevelopment #Frontend #Performance #CodingTips #SoftwareEngineering
To view or add a comment, sign in
-
🚀React Bundle Analysis & Optimization Your React app might look fine… But if your bundle is heavy, users will feel the slowdown ⚠️ Let’s break this down simply 👇 🧩 What is a Bundle? 👉 When you build a React app, all your code + libraries are combined into JavaScript files (bundles) 💡 Example: • React • UI libraries • Utility functions ➡️ All packed into one or multiple JS files ⚠️ Why Large Bundles Are a Problem ❌ Slow initial load ❌ More JavaScript to execute ❌ Poor performance on low-end devices 👉 Bigger bundle = Slower app 🔍 What is Bundle Analysis? 👉 It helps you understand: • Which library is heavy • What is increasing bundle size • Where optimization is needed 📊 Tools give a visual breakdown of your bundle 🛠️ Tools You Can Use ✔ webpack-bundle-analyzer ✔ source-map-explorer 👉 Shows which dependency is taking the most space ⚡ How to Optimize Bundle 🧩 1. Code Splitting → Break bundle into smaller chunks ⚡ 2. Lazy Loading → Load components only when needed 🌳 3. Tree Shaking → Remove unused code automatically 📦 4. Dynamic Imports → Load heavy modules on demand 🧹 5. Remove Heavy Libraries → Replace with lighter alternatives 🔥 Real Impact ✔ Faster load time ✔ Better performance ✔ Improved user experience ✔ Smaller bundle size 🧠 Simple Way to Understand • Without Optimization → Big bundle → Slow app ❌ • With Optimization → Small chunks → Fast app ✅ 💬 Have you ever checked what’s inside your bundle? #React #WebPerformance #Frontend #JavaScript #WebDevelopment #Optimization #Coding #SoftwareEngineering
To view or add a comment, sign in
-
-
Your React app feels slow, and you have no idea why. The truth is, it is probably re-rendering 10x more than it should be. React core philosophy is that UI is a function of state. When state changes, React re-evaluates the component tree. But if you are not careful, a single state change at the top of your tree can trigger a massive wave of unnecessary re-renders all the way down to the bottom. Here are the 3 most common reasons your React app is re-rendering too much: 1. Passing new object references in props. If you pass an inline object or function like style={{ color: 'red' }} or onClick={() => doSomething()}, React sees a brand new reference on every single render. Even if the contents are identical, React thinks the prop changed. 2. State lifted too high. If you have a form input that updates on every keystroke, and its state lives in a parent component alongside heavy data tables, typing one letter re-renders the entire table. 3. Missing memoization. Complex calculations or heavy child components that do not depend on the changed state will still re-render by default. React is fast, but it is not magic. Example: Instead of passing inline functions like this: <Button onClick={() => handleSubmit()} /> Use useCallback to keep the reference stable: const handleSubmit = useCallback(() => { ... }, []); <Button onClick={handleSubmit} /> Key takeaways: - Keep state as close to where it is used as possible. - Use memo for expensive child components. - Use useMemo and useCallback to preserve reference equality for objects and functions passed as props. #reactjs #webdevelopment #frontend #javascript #performance #softwareengineering #coding #webdev #reactdeveloper #programming
To view or add a comment, sign in
-
-
Your React app works. But is it fast? ⚡ Here are 11 performance tips every React dev should know: 1️⃣ React.memo → prevent unnecessary re-renders 2️⃣ useMemo → cache expensive calculations 3️⃣ useCallback → stable function references 4️⃣ Lazy load components → smaller initial bundle 5️⃣ Virtualize long lists → use react-window 6️⃣ Keep state local → don't over-use Redux/Context 7️⃣ Cache API responses → use React Query or SWR 8️⃣ Optimize images → WebP + loading="lazy" 9️⃣ Avoid layout thrashing → batch DOM reads & writes 🔟 No inline objects in JSX → define styles outside render 1️⃣1️⃣ Code split → dynamic imports for heavy components The golden rule? Profile first with React DevTools. Then optimize where it actually matters. Premature optimization is still a trap. 😅 Which of these do you already use? Drop it below 👇 #ReactJS #JavaScript #Frontend #WebPerformance #TechTips #WebDevelopment #FullStack
To view or add a comment, sign in
-
⚡ A Simple React Performance Trick: Lazy Loading Components One performance issue I’ve noticed in many React applications is large bundle sizes. When an app loads too much JavaScript upfront, it can slow down the initial page load and impact user experience. One simple solution for this is Lazy Loading. Instead of loading all components at once, we can load them only when they are needed. Here’s a simple example 👇 import React, { lazy, Suspense } from "react"; const Dashboard = lazy(() => import("./Dashboard")); function App() { return ( <Suspense fallback={Loading...}> ); } What’s happening here? 🔹 React.lazy() loads the component only when it is rendered 🔹 Suspense shows a fallback UI while the component is loading 🔹 This reduces the initial bundle size Why this matters 👇 ✅ Faster initial page load ✅ Better performance for large applications ✅ Improved user experience This technique becomes especially useful for: • Dashboards • Admin panels • Large feature modules • Route-based components 💡 One thing I’ve learned while working with React: Small performance optimizations like lazy loading and code splitting can make a big difference as applications scale. Curious to hear from other developers 👇 Do you use lazy loading in your React applications? #reactjs #frontenddevelopment #javascript #webdevelopment #reactperformance #softwareengineering #coding
To view or add a comment, sign in
-
-
Most Node.js apps don't crash because of bad code. They crash because of bad error handling. Here's a pattern I use in almost every project: Instead of letting unhandled promise rejections silently kill your server, wrap your async route handlers in a reusable utility: const asyncHandler = (fn) => (req, res, next) => { Promise.resolve(fn(req, res, next)).catch(next); }; app.get('/user/:id', asyncHandler(async (req, res) => { const user = await getUserById(req.params.id); if (!user) throw new AppError('User not found', 404); res.json(user); })); app.use((err, req, res, next) => { res.status(err.status || 500).json({ message: err.message || 'Internal Server Error', }); }); That's it. One wrapper, one central error middleware, and your entire app handles errors consistently. The key insight: errors should flow to one place, not be scattered across every route with try/catch blocks copy-pasted everywhere. A custom AppError class lets you attach HTTP status codes and meaningful messages, so your API responses stay predictable for frontend teams. This also makes logging much easier — you intercept everything in one middleware and send it to whatever logging service you use. Small pattern, big payoff. Your teammates will thank you, and your on-call rotations will get a lot quieter. What's the error handling pattern you swear by in your Node.js projects — do you use something similar, or have you found a better approach? #nodejs #backend #javascript #softwaredevelopment #webdevelopment
To view or add a comment, sign in
-
-
I stopped guessing… and started measuring my React app For a long time, I thought I knew why my React app was slow. ❌ Maybe too many re-renders ❌ Maybe React is inefficient ❌ Maybe my code is bad ------------------------------------- But the truth? 👉 I was guessing… not measuring. ⚡ Then I discovered the real game changer: Profiling Instead of assumptions, I started using: • React DevTools Profiler • Chrome Performance tab ------------------------------------- And suddenly, everything became clear 👇 🔍 What I found: • Components re-rendering unnecessarily • Expensive calculations running on every render • Large lists blocking the UI • State updates triggering deep component trees ------------------------------------- 💡 Fixes I applied: ✅ Memoized components using React.memo ✅ Used useMemo for heavy computations ✅ Used useCallback to avoid unnecessary function recreation ✅ Split large components into smaller ones ✅ Virtualized long lists ------------------------------------- 🚀 The result: Not just “slightly better”… 👉 The app became noticeably faster and smoother 🎯 Biggest lesson: Performance issues are not solved by guessing They are solved by measuring #reactjs #reactdeveloper #seniorfrontend #frontendengineering #javascript #webperformance #reactperformance #frontendarchitecture #softwareengineering #webdevelopment #performanceoptimization #cleancode #scalablecode #devtools #profiling #engineeringlife #techlead #frontenddev #softwaredeveloper #codingbestpractices #uilayer #webperf #performancematters
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