🚀 Day 10/30 – useCallback (Deep Dive Most Devs Ignore) You’ve probably heard: 👉 “useCallback is for performance optimization” But here’s the truth most people don’t understand 👇 💡 useCallback does NOT make your function faster. It makes your reference stable. 🧠 What actually happens behind the scenes Every render in React creates new function instances: const handleClick = () => { console.log("Clicked"); }; Even if code looks same → memory reference is different ❌ ⚠️ Why this becomes a problem When you pass functions to child components: <Child onClick={handleClick} /> React compares props using shallow comparison 👉 New function reference = React thinks props changed 👉 Child re-renders unnecessarily 🔁 🔥 Enter useCallback const handleClick = useCallback(() => { console.log("Clicked"); }, []); Now React: ✅ Stores the function ✅ Returns SAME reference on re-render ✅ Prevents unnecessary child re-renders 🧩 Where useCallback actually matters ✔️ When passing functions to memoized components (React.memo) ✔️ When functions are dependencies in useEffect ✔️ In large lists (performance-sensitive UIs) 🚫 When NOT to use it (very important) ❌ Small components ❌ No prop drilling ❌ No performance issue 👉 Overusing useCallback can make your app slower due to extra memory & tracking ⚙️ Advanced Insight (rarely discussed) useCallback internally behaves like: useCallback(fn, deps) === useMemo(() => fn, deps) 👉 It memoizes the function reference, not the result 🧨 Hidden Bug Developers Face const handleClick = useCallback(() => { console.log(count); }, []); 👉 This will log stale value of count Why? Because dependency array is empty ❗ ✅ Correct: }, [count]); 🔥 Key Takeaway useCallback is NOT a performance tool by default It’s a reference stability tool 👉 Use it ONLY when it prevents unnecessary work 💬 If this clicked for you, comment “REFERENCE ⚡” and I’ll share a real-world optimization example next. #ReactJS #UseCallback #Hooks #WebDevelopment #Frontend #JavaScript #CodingJourney #LearnInPublic
React useCallback: Reference Stability Not Performance Optimization
More Relevant Posts
-
You wrapped your component in React.memo… but it still re-renders 🤔 I ran into this more times than I’d like to admit. Everything looks correct. You’re using React.memo. Props don’t seem to change. But the component still re-renders on every parent update. Here’s a simple example: const List = React.memo(({ items }) => { console.log('List render'); return items.map(item => ( <div key={item.id}>{item.name}</div> )); }); function App() { const [count, setCount] = React.useState(0); const items = [{ id: 1, name: 'A' }]; return ( <> <button onClick={() => setCount(count + 1)}> Click </button> <List items={items} /> </> ); } When you click the button the List still re-renders. At first glance, it feels wrong. The data didn’t change… so why did React re-render? The reason is subtle but important: every render creates a new array. So even though the content is the same, the reference is different. [] !== [] And React.memo only does a shallow comparison. So from React’s perspective, the prop did change. One simple fix: const items = React.useMemo(() => [ { id: 1, name: 'A' } ], []); Now the reference stays stable and memoization actually works. Takeaway React.memo is not magic. It only helps if the props you pass are stable. If you create new objects or functions on every render, you’re effectively disabling it without realizing it. This is one of those bugs that doesn’t throw errors… but quietly hurts performance. Have you ever debugged something like this? 👀 #reactjs #javascript #frontend #webdevelopment #performance #reactperformance #softwareengineering #programming #coding #webdev #react #typescript
To view or add a comment, sign in
-
-
🚀 Why useState is a Game-Changer in React. let's breakdown this 👇 💡 What is useState? "useState" is a React Hook that allows you to store and manage dynamic data (state) inside functional components. Without it, your UI wouldn’t respond to user input. 📱 Real-Time Example: Form Input & Validation Let’s take a simple login form 👇 import React, { useState } from "react"; function LoginForm() { const [email, setEmail] = useState(""); const [error, setError] = useState(""); const handleSubmit = (e) => { e.preventDefault(); if (!email.includes("@")) { setError("Please enter a valid email address"); } else { setError(""); alert("Form submitted successfully!"); } }; return ( <form onSubmit={handleSubmit}> <input type="text" placeholder="Enter email" value={email} onChange={(e) => setEmail(e.target.value)} /> {error && <p style={{ color: "red" }}>{error}</p>} <button type="submit">Submit</button> </form> ); } export default LoginForm 🧠 What’s happening here? - "email" → stores user input - "setEmail" → updates input as the user types - "error" → stores validation message - "setError" → shows/hides error instantly useState is what connects user actions to UI behavior. It ensures your forms are not just functional, but smart and responsible 💬 Have you implemented form validation using useState? What challenges did you face? #ReactJS #FrontendDevelopment #JavaScript #WebDevelopment #Coding
To view or add a comment, sign in
-
Nobody told me this when I started React. I used it for over a year without really getting it. I could build things. Components, hooks, state — all of it. But something was always slightly off. Like, I was constantly fighting the framework instead of working with it. I'd update the state and then immediately try to read it. I'd wonder why my UI wasn't reflecting what I just changed. I'd add more useEffects, trying to force things to sync. More code. More confusion. Then I came across three characters that broke it all open for me. UI = f(state) That's it. React has one rule. Your UI is not something you control directly — it's the output of a function. You give it your data. It gives you back what the screen should look like. You don't say "update this element." You say, "here's the data." React handles the screen. I know that sounds simple. But I genuinely wasn't thinking this way. I was still mentally treating React like jQuery — find the element, change it, done. That mental model works fine for jQuery. In React it fights you every step. The moment I stopped thinking about updating UI and started thinking about describing UI — everything got easier. My components got smaller. My bugs got fewer. My useEffects stopped multiplying. Because I finally understood: my only job is to get the state right. React's job is everything else. #React #JavaScript #Frontend #ReactJS #WebDevelopment #Programming #100DaysOfCode #SoftwareDevelopment
To view or add a comment, sign in
-
-
Most React developers think components re-render randomly. They don’t. React actually follows a Depth-First Traversal strategy — and once I understood this, a lot of React’s "weird" behavior suddenly started making sense. 👇 When React updates UI, it doesn't jump around the component tree. It dives deep first — parent → child → child — until it reaches the leaf node. Only then does it backtrack and move to the next sibling. Here’s how React traverses the tree: 🔹 Start from the Root React begins from the root — the top of your component tree. 🔹 Go Deep (Child by Child) It keeps moving downward — first child → next child → until the deepest node. 🔹 Backtrack & Move to Sibling Once React hits a leaf, it goes back to the parent, checks for siblings, and repeats. Now here’s why this matters: ⚡ Fast & Predictable React walks the tree in O(n) — touching each node only once. 🧠 Smart Diffing • If element types change (div → span), React replaces the subtree • For lists, keys help React reuse and reorder nodes efficiently Now the interesting part 👇 This traversal existed even before React Fiber (pre-React 16). But earlier, reconciliation was all-or-nothing. Large component trees could block the main thread and hurt performance. With React 16 (Fiber), traversal became: ⏸️ Interruptible React can pause rendering to handle high-priority updates (like user input) 🔄 Incremental It resumes from where it left off — instead of restarting everything So yes, Depth-First Traversal was always there. React Fiber just made it work with time, not against it. I recently started digging deeper into React internals, and honestly, it’s changing how I structure components and debug performance issues. If you're also exploring React beyond hooks and state — we're probably like-minded. Let’s connect and learn together 🚀 #React #ReactJS #Frontend #WebDevelopment #JavaScript #ReactFiber #SoftwareEngineering #FrontendDevelopment #ReactInternals
To view or add a comment, sign in
-
-
React ships a 42KB runtime to every user. Svelte ships 0KB. That's not a marketing claim. It's how the compiler works. Here's why Svelte beats React at a fundamental level — and why most devs don't talk about it: THE CORE DIFFERENCE React = a runtime library that ships to the browser. Svelte = a compiler that disappears at build time. React does its work at RUNTIME: • Virtual DOM diffing on every state change • Reconciler figuring out what changed • 42KB of framework overhead on every page Svelte does its work at BUILD TIME: • Compiler reads your code and generates direct DOM updates • No virtual DOM. No reconciler. • 0KB framework in the final bundle THE NUMBERS (same counter app) React: Bundle size: ~42KB gzip (just the framework) DOM update: diff entire component tree → find change → patch DOM Svelte: Bundle size: ~1.5KB gzip DOM update: directly calls document.getElementById().textContent = value That's not Svelte being clever. That's the compiler writing the DOM update code for you. REACTIVITY: SVELTE IS JUST JS React (mental overhead): const [count, setCount] = useState(0); setCount(prev => prev + 1); // can't just do count++ Svelte: let count = 0; count++; // this is it. compiler handles reactivity. No hooks. No dependency arrays. No stale closure bugs. WHAT THIS MEANS FOR PERFORMANCE Svelte wins on: → Bundle size (no 42KB runtime tax) → Runtime speed (direct DOM, no VDOM overhead) → Memory usage (no virtual DOM tree in memory) → Core Web Vitals (smaller bundle = better LCP + TTI) React wins on: → Ecosystem size (more libraries, more jobs) → Team familiarity → Large app architecture patterns Is React going away? No. Should every new project default to React? Probably not. For performance-critical apps, dashboards, and marketing sites — Svelte is fundamentally the smarter technical choice. React is great. Svelte is better on the fundamentals. Do you agree? Disagree? Let's discuss below. #svelte #react #javascript #frontend #webperformance #webdev
To view or add a comment, sign in
-
-
React Fiber: what it actually means for your code Most React devs know what Fiber is by name. Fewer know why it matters day to day. The old reconciler worked synchronously. State changes, React walks the whole tree, diffs it, writes to the DOM. One pass, no stopping. On a large component tree that blocked the main thread long enough for users to notice — animations stuttered, inputs lagged. Fiber fixed this by replacing the recursive call stack with a linked list. Each fiber is a plain object: component type, props, state, and pointers to parent, first child, next sibling. React now owns the execution, so it can pause whenever something more urgent comes in. Work splits into two phases, and this is the part worth understanding. The render phase builds a work-in-progress tree in memory without touching the DOM. React can stop mid-tree, hand control back to the browser for a keypress or a frame, then continue. If a higher-priority update arrives, it discards the in-progress work and starts over. The commit phase doesn't pause. Once the tree is ready, React applies all DOM mutations in one go. This part has to be synchronous — a half-applied DOM update breaks the UI. Here's where it connects to your actual code. useTransition works because React can genuinely deprioritize a state update and interrupt it if needed. Without Fiber, marking something as "non-urgent" would be meaningless — the old reconciler couldn't stop anyway. Suspense pauses a subtree while data loads for the same reason. React keeps the current tree on screen, builds the new one in the background, swaps when ready. Slow renders that only appear under load, inputs that lag when a big list re-renders, Suspense boundaries not behaving as expected — all of these trace back to how Fiber schedules and interrupts work. When something's off and the profiler gives you a confusing flamegraph, knowing that React works in two phases (one interruptible, one not) usually tells you where to look. #react #frontend #javascript #webdev #reactjs #frontenddevelopment #softwaredevelopment
To view or add a comment, sign in
-
-
🔁 DRY in React & Next.js — Stop Writing the Same Code Twice DRY = Don't Repeat Yourself. One of the simplest principles. Also one of the most violated ones in large React codebases. Here's how to actually apply it 👇 ❌ The Problem — Copy-Paste Components How many times have you seen this? <UserProfileCard /> and <AdminProfileCard /> — same layout, same styles, slightly different data. Written twice. Maintained twice. Broken twice. ✅ The Fix — Abstraction at Every Layer 1. Reusable Components Extract shared UI into a single generic component. One <ProfileCard role="admin" /> beats two separate components every time. 2. Custom Hooks If two components share the same useEffect + useState logic — that's a custom hook waiting to be born. useFetchUser(), useDebounce(), useLocalStorage() — write once, use everywhere. 3. Utility Functions Date formatting, price calculation, string truncation — these don't belong inside components. Move them to /utils and import them across your entire app. 4. Next.js Layouts Stop repeating <Navbar /> and <Footer /> on every page. That's what layout.tsx is for. One definition. Every page benefits. 5. Constants & Config Magic strings and numbers scattered across 40 files is a maintenance nightmare. Centralize them. One change. Zero bugs from inconsistency. ⚠️ But Don't Over-DRY DRY doesn't mean "merge everything that looks similar." Two things that look the same today may diverge tomorrow. Premature abstraction is its own kind of technical debt. The rule: duplicate once, abstract on the third time. DRY code isn't about being clever — it's about respecting your future self (and your teammates) at 11pm before a deadline 😄 What's the worst copy-paste mess you've ever inherited in a codebase? 👇 #React #NextJS #DRY #CleanCode #FrontendDevelopment #WebDev #SoftwareEngineering
To view or add a comment, sign in
-
-
React vs. Redux vs. Redux Toolkit: Which should you use? "Do I need Redux?" is still one of the most common questions in frontend development. State management can be overwhelming, but understanding the evolution of these tools makes the choice much clearer. Here is a straightforward breakdown of the big three: 1️⃣ React State & Context (The Foundation) React’s built-in hooks (useState, useReducer, useContext) are often all you need. The Good: Zero extra dependencies. It is perfect for local component state (like form inputs or UI toggles) and low-frequency global state (like user themes or auth status). The Bad: Relying purely on Context for high-frequency, complex global state can lead to unnecessary re-renders and messy prop-drilling. 2️⃣ Classic Redux (The Legacy Heavyweight) Redux revolutionized how we handle global state by introducing a single, predictable source of truth. The Good: Unmatched predictability and incredible developer tools (time-travel debugging is magic). The Bad: The boilerplate. Writing separate files for actions, action types, and reducers slows down development and frustrates teams. 3️⃣ Redux Toolkit / RTK (The Modern Standard) Redux Toolkit is not a replacement for Redux; it is the official, modern way to write it. It takes everything great about Redux and strips away the pain points. The Good: It drastically reduces boilerplate. Features like createSlice automatically generate your actions and reducers. It includes Immer under the hood (allowing you to write simpler, "mutating" logic that updates state immutably), and it ships with RTK Query for incredibly efficient data fetching and caching. The Verdict: If you are starting a new project that genuinely needs Redux, RTK is the only way you should be writing it. 💡 My Rule of Thumb: Start simple. Build with React's built-in state. When your state starts feeling tangled, difficult to track, or requires passing props through five layers of components (Prop Drilling)—it's time to bring in Redux Toolkit. How is your team handling state management these days? Are you firmly on team RTK, or have you pivoted to lighter alternatives like Zustand or Jotai? Let's discuss in the comments! 👇 #ReactJS #Redux #WebDevelopment #Frontend #SoftwareEngineering #JavaScript
To view or add a comment, sign in
-
-
🚀 React.js! Getting more comfortable with React now! Today I explored one of the most important hooks — useEffect. 💡 What I learned today: • useEffect for handling side effects • Fetching data from APIs • Component lifecycle basics in React • Clean and efficient code structure 👨💻 Tried a simple example: import React, { useState, useEffect } from "react"; function Users() { const [users, setUsers] = useState([]); useEffect(() => { fetch("https://lnkd.in/g7MrTyES") .then((res) => res.json()) .then((data) => setUsers(data)); }, []); return ( <div> <h2>User List</h2> {users.map((user) => ( <p key={user.id}>{user.name}</p> ))} </div> ); } export default Users; This helped me understand how React handles data fetching and updates the UI dynamically ⚡ Slowly building confidence and consistency 💪 If you have any tips, resources, or beginner project ideas, feel free to share 🙌 #ReactJS #JavaScript #FrontendDevelopment #WebDevelopment #Coding #Programming #Developer #SoftwareDeveloper #LearningJourney #Day3 #100DaysOfCode #CodeNewbie #Tech #UI #WebDev #ReactHooks #useEffect #APIs #Frontend #CodingLife #Developers #TechCommunity #LearnInPublic
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