🚀 Code Capsule Weekly – Capsule #7
Better API Error Handling, React Optimization Gotcha, and a Tricky Number Puzzle
👋 Welcome Back!
Hey devs! 👋
Welcome to Capsule #7 - your weekly shot of clean code practices, developer wisdom, and fun mental workouts.
This week, we’re covering:
✅ Smarter API error handling with fetch
✅ A React memoization pitfall that fools even pros
✅ A subtle JS behavior tip for beginners
✅ A code challenge that might make you double-check your math
Let’s dive in. 👇
📂 Snippet of the Week – Clean Error Handling with Fetch
We’ve all done this:
Here’s a safer pattern you can reuse everywhere:
Usage:
✅ Centralized error formatting
✅ Fails gracefully
✅ Works with async/await
or SWR/React Query
💡 Programming Tip – Don’t Overuse React.memo
It sounds like a performance win, but React.memo
can hurt performance if misused.
Example:
Here’s the catch:
🔸 If the props change often, memoization is wasted
🔸 It adds overhead by checking equality
🔸 It only helps if re-renders are expensive and props stay the same
📌 Use React.memo
for:
Heavy components
Static props
Re-render bottlenecks you've measured
💡 Don’t memoize by default, measure first.
👶 Beginner Tip – parseInt('08')
Can Be Dangerous
This old JavaScript quirk has tripped up devs for years:
parseInt('08') // ✅ 8
parseInt('08', 10) // ✅ 8
parseInt('08', 8) // ❌ 0 – treated as octal!
👉 Always pass the radix to parseInt
:
parseInt('08', 10); // ✅
parseInt('010', 2); // ✅ binary
This ensures your numbers are interpreted the way you expect.
🔍 Quick Snippet – Remove Empty Values from an Object
Here’s a clean one-liner to strip null
, undefined
, or empty string values:
const cleanObject = (obj) =>
Object.fromEntries(Object.entries(obj).filter(([_, v]) => v != null && v !== ''));
Input:
{ name: 'Kaveen', age: null, country: '', active: true }
Output:
{ name: 'Kaveen', active: true }
📦 Super useful before sending data to an API.
🧩 Code Challenge – Missing Number in a Series
You have an array of unique numbers from 1
to N
(inclusive), but one number is missing.
Write a function to find the missing number:
findMissing([1, 2, 4, 5]); // Output: 3
findMissing([3, 1, 2, 6, 5]); // Output: 4
⚠️ Optimize for performance and try to avoid loops inside loops.
💡 Think: sum of N formula!
Tag #CodeCapsuleChallenge or reply to this post with your solution!
💭 Insight of the Week
“Most bugs aren’t complex, they’re subtle.”
It’s rarely the 500-line monster that breaks things.
It’s the one-line edge case, the missing null
check, the misunderstood return value.
Train your eye to see the subtle stuff.
💬 Comment your thinking
🔍 Use linters
🧪 Write small tests
📦 And when something feels “off,” dig in.
🚀 That’s a Wrap!
Thanks for joining this week’s capsule!
I hope you walk away with a sharper mind, a safer API strategy, and cleaner React code.
✅ Got feedback? I’d love to hear it
📣 Post your challenge solutions on social with #CodeCapsuleWeekly
Until next week,
Happy coding!