🧠 Day 24 — Optional Chaining (?.) & Nullish Coalescing (??) Tired of errors like “Cannot read property of undefined”? 🤔 These two operators will save you 🚀 --- ⚡ 1. Optional Chaining ?. 👉 Safely access nested properties const user = { profile: { name: "John" } }; console.log(user.profile?.name); // John console.log(user.address?.city); // undefined (no error) 👉 Stops execution if value is null or undefined --- ⚡ 2. Nullish Coalescing ?? 👉 Provides a default value only if value is null or undefined const name = null; console.log(name ?? "Guest"); // Guest --- ⚠️ Difference from || console.log(0 || "Default"); // "Default" ❌ console.log(0 ?? "Default"); // 0 ✅ 👉 || treats falsy values (0, "", false) as false 👉 ?? only checks null or undefined --- 🚀 Why it matters ✔ Prevents runtime errors ✔ Cleaner and safer code ✔ Widely used in APIs & React apps --- 💡 One-line takeaway: 👉 “Use ?. to safely access, ?? to safely default.” --- Once you start using these, your code becomes much more robust. #JavaScript #ES6 #OptionalChaining #WebDevelopment #Frontend #100DaysOfCode 🚀
Optional Chaining & Nullish Coalescing in JavaScript
More Relevant Posts
-
Day 8 — Today my frontend talked to the outside world for the first time. Fetched real data from a public API. Rendered it on screen. It's genuinely exciting every time. async/await cleaned up my fetch code significantly compared to chaining .then() everywhere. But I also finally understood why promises exist — it's not just about syntax. The part most tutorials skip: error handling. What happens when the API is down? What does your UI show? I spent extra time making sure loading and error states were actually handled, not just happy path. Also tried Axios for the first time. The automatic JSON parsing and nicer error messages are worth it for bigger projects. Built a small app that shows GitHub user info by username. Feels like a real tool now. How do you handle API errors in your projects? #javascript #webdev #reactjs #frontenddeveloper
To view or add a comment, sign in
-
🧠 The bug wasn’t in my code… It was in my assumption. I spent 2 hours debugging a UI issue where a list wasn’t updating correctly. The logic looked fine. The API response was correct. State was updating. So what was wrong? 👇 👉 I was using the array index as the key in a dynamic list. At first, everything worked. But the moment I added/removes items… things broke in weird ways. 💥 Items re-rendered incorrectly 💥 State got mixed up between components 💥 UI started behaving unpredictably 💡 Lesson learned: Keys in React are not just for removing warnings. They are how React tracks identity. Using index as a key = telling React: "Yeah, these items might change… but pretend they didn’t." 🛠️ Better approach: Always use a unique and stable id from your data. 🧠 Simple way to think: React uses keys like names in a classroom. If everyone has the same name (or changing names), things get chaotic. 🔥 Takeaways: • Avoid index as key (especially in dynamic lists) • Stable identity = predictable UI • Many “random bugs” come from small decisions like this 💬 Have you ever faced a weird UI bug that turned out to be something small? #ReactJS #FrontendDevelopment #JavaScript #WebDev #CodingMistakes
To view or add a comment, sign in
-
Every React codebase has a junk drawer component. You know the one. Open the useEffect and find: data fetching, a DOM subscription, an analytics call, a state sync with localStorage, and a resize listener. Five different jobs. One hook. Zero separation. It happens because useEffect is the only place React gives you to say 'do something after render'. So everything that doesn't fit neatly into JSX or state gets thrown in there. The problem isn't useEffect. It's that one hook is doing five unrelated things with one shared lifecycle. When any dependency changes, everything in that effect re-runs. Your analytics fires again. Your subscription resets. Your fetch triggers for the wrong reason. I started splitting effects by job, not by timing. One effect for the fetch. One for the subscription. One for analytics. Each with its own cleanup. Its own dependencies. It felt like more code. But each effect became debuggable in isolation. When the fetch broke, I didn't have to read through subscription logic to find the bug. useEffect isn't a lifecycle method. It's a synchronization primitive. When you treat it like componentDidMount, you get a junk drawer. When you treat it like "keep this in sync with that", you get clarity. #ReactJS #Frontend #SoftwareArchitecture #WebDevelopment #CodeQuality
To view or add a comment, sign in
-
Spent hours chasing a bug that turned out to be a typo? We've all been there. My latest debugging saga involved a React component rendering incorrect data. The state was updating, but the UI wasn't reflecting the 𝐥𝐚𝐭𝐞𝐬𝐭 𝐯𝐚𝐥𝐮𝐞𝐬 immediately. 💡 I was pulling my hair out inspecting network requests and reducer logic. Turns out, the issue was a classic `useEffect` pitfall. My dependency array was missing a key variable, causing the effect to run with a 𝐬𝐭𝐚𝐥𝐞 𝐜𝐥𝐨𝐬𝐮𝐫𝐞. 🧠 A simple addition to `[dependency]` fixed hours of frustration. This reinforces how much 𝐜𝐨𝐧𝐭𝐞𝐱𝐭 𝐦𝐚𝐭𝐭𝐞𝐫𝐬 in component lifecycles. Always double-check your `useEffect` dependencies; they're often the silent culprits behind subtle React bugs. What's your go-to strategy when `useEffect` dependencies bite you? #ReactJS #FrontendDevelopment #DeveloperTips
To view or add a comment, sign in
-
🚀 I fixed a performance issue… without adding a single library Most developers think: 👉 “App slow? Install something.” I used to do the same. But recently, I debugged a production issue where pages were lagging badly. Instead of adding tools, I looked at the fundamentals 👇 ⚠️ What I found: - Components re-rendering unnecessarily - Duplicate API calls hitting the backend - Heavy logic running on every render - Unused components still being loaded No fancy tools. Just bad decisions. --- ✅ What I changed: - Controlled re-renders (memoization + better state structure) - Removed duplicate API calls - Used dynamic imports properly in Next.js - Cleaned up unused code --- 📉 Result: - Faster page load - Better Lighthouse score - Noticeably smoother UI --- 💡 Biggest lesson: Performance is not about adding more… 👉 It’s about understanding what your code is actually doing Sometimes the best optimization is: removing things, not adding --- Curious 👇 What’s one performance mistake you’ve seen (or made)? #ReactJS #NextJS #FrontendDevelopment #WebPerformance #SoftwareEngineering #CleanCod
To view or add a comment, sign in
-
Don't hijack your user's session. Give them a choice. 🤝 Pushing a new deployment to production is great but forcing a page reload while a user is mid-form or mid-scroll? Not so great. In my latest article, I explore how to handle New Release Refreshes in React using React Query. I compare two distinct strategies: 🔹 Soft Updates: The "Gentle" approach. Show a notification/toast letting the user know a new version is available. They decide when to refresh. 🔹 Hard Updates: The "Critical" approach. Forcing a page reload to ensure the UI and API stay in perfect sync. I break down exactly how to implement this logic so you can stop "surprising" your users with sudden reloads and start providing a polished, professional update experience. Read the full guide here: https://lnkd.in/dChnpQ49 Github repo: https://lnkd.in/dxTRANMf #ReactJS #UserExperience #ReactQuery #WebDev #FrontendArchitecture
To view or add a comment, sign in
-
-
Most performance issues aren’t complex - they’re ignored basics. We proved it by cutting our load time from 4.2s to 1.4s. No magic. Just fundamentals applied correctly 𝗕𝗲𝗳𝗼𝗿𝗲: → Entire JS bundle loaded upfront → Full-resolution images served to all devices → Every component re-rendering on any state change → API calls fired on every keystroke 𝗔𝗳𝘁𝗲𝗿: → Code splitting with React.lazy() - only load what the route needs → Images lazy-loaded with proper sizing and WebP format → React.memo + useCallback to stop unnecessary re-renders → Debounced inputs - API calls only after user stops typing The result? 4.2s → 1.4s load time. 35% improvement in user engagement. The biggest takeaway: performance isn't a feature you add at the end. It's a habit you build from day one. What's the one optimization that made the biggest impact in your project? #Frontend #Performance #ReactJS #CoreWebVitals #WebDev
To view or add a comment, sign in
-
I keep running into the same issue when building forms with React Hook Form + MUI. At the beginning everything feels clean. Then you start adding: - conditional fields - validation rules - async data …and suddenly: - Controller everywhere - watch() scattered across the component - manual error wiring - logic split between JSX and form config It works, but it doesn’t feel right anymore. After working on several enterprise projects, I noticed this pattern keeps repeating. Forms are simple… until they aren’t. Curious how others are dealing with this. Do you keep scaling with RHF + MUI as-is, or do you introduce some abstraction at some point? #reactjs #frontend
To view or add a comment, sign in
-
“We just added login…” - and a week later we refactored half of the frontend. Ran into a very familiar situation recently. Backend “slightly” changed: now a user is not just a token, but also a context — company, branch, role, permissions. Sounds reasonable. In reality, your frontend starts behaving like a teenager: random 403s “no permissions” here “context not selected” there and sometimes… it works (no idea why) We had two options: 👉 patch it with if-statements 👉 hardcode a few checks 👉 “we’ll fix it later” And end up with: a fragile mess no one wants to touch Instead, we did something boring but right: enabled cookie sessions (withCredentials) introduced a proper flow after login (login → context → work) moved permissions to context (not login) normalized API responses implemented real logout (not just “delete token and pray”) Here’s the funny part: 👉 nothing changed visually 👉 users didn’t notice anything But under the hood: one user can belong to multiple companies roles differ per branch backend actually enforces access frontend stops guessing and starts following rules Big takeaway: the most important changes are the ones users never see And yeah, the classic: “Let’s just ship the feature, we’ll fix it later” No 🙂 Sometimes you need to lay the rails first, otherwise the train will move… just not where you expect. P.S. If your frontend starts acting weird after “small backend changes” - it’s probably not a bug. It’s architecture reminding you it exists 🙂 https://hahazen.com/ #frontend #webdevelopment #softwareengineering #javascript #reactjs #nextjs #api #backend #fullstack #webdev #architecture #systemdesign #rbac #authentication #authorization #cookies #session #apiintegration
To view or add a comment, sign in
-
-
🚀 5 React Mistakes I Made as a Beginner (And How to Fix Them) When I first started building with React, I made a lot of mistakes that slowed me down and introduced bugs I couldn't explain. Here are 5 of the most common ones — and how to fix them: ❌ #1 — Not cleaning up useEffect Forget to return a cleanup function? Hello, memory leaks. ✅ Always return a cleanup for timers, event listeners, and subscriptions. ❌ #2 — Using index as a key in lists This breaks React's reconciliation and causes weird UI bugs. ✅ Always use a unique ID from your data as the key prop. ❌ #3 — Calling setState directly inside render This creates an infinite re-render loop. ✅ Keep state updates inside event handlers or useEffect only. ❌ #4 — Fetching data without handling loading and error states Your UI breaks or shows nothing while data loads. ✅ Always manage three states: loading, error, and success. ❌ #5 — Putting everything in one giant component Hard to read, hard to debug, impossible to reuse. ✅ Break your UI into small, focused, reusable components. These mistakes cost me hours of debugging. I hope sharing them saves you that time. If you found this helpful, feel free to repost ♻️ — it might help another developer on their journey. 💬 Which of these mistakes have you made? Drop a comment below! #React #JavaScript #WebDevelopment #Frontend #MERNStack #ReactJS #100DaysOfCode #CodingTips #Developer
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