If props don’t change, why does a component still re-render? Many developers believe that if the props are the same, the component won’t re-render. However, this isn't always the case. Consider the following example: function Parent() { const [count, setCount] = useState(0); return <Child name="Sajal" />; } In this scenario, even though the name prop never changes, the Child component will still re-render. This happens because when the Parent component re-renders, React re-runs the Child component as well. So, how can we prevent unnecessary re-renders? The solution is to use React.memo. This function tells React to only re-render the component if the props actually change. Here’s how it looks: const Child = React.memo(({ name }) => { console.log("Rendered"); return <div>{name}</div>; }); With this implementation, the Child component will not re-render unless the name prop changes. Key Insight: React re-renders by default, and optimization is something you explicitly control. Important Note: React.memo uses shallow comparison, so objects and functions may still cause re-renders. #ReactJS #JavaScript #FrontendDevelopment #WebDevelopment #SoftwareEngineering #CodingJourney #LearninglnPublic #DeveloperLife #ReactInternals #FrontendEngineer #TechInterview #StateManagement
Sajal Shrivastav’s Post
More Relevant Posts
-
⚡ React.memo is NOT free. Most developers use it wrong. Here’s when it actually helps — …and when it silently makes things worse 👇 ✅ Use React.memo when: • A child component receives the same props often • The parent re-renders frequently (e.g. on every keystroke) • The child is expensive to render ❌ Skip React.memo when: • Props change every render anyway (new object/array inline) • The component is already fast • You haven’t profiled yet 💡 The real gotcha: // ❌ memo does nothing here — new array on every render <MemoChild items={[1, 2, 3]} /> // ✅ stable reference = memo works const items = useMemo(() => [1, 2, 3], []); <MemoChild items={items} /> 🧠 Why this happens: React.memo does a shallow comparison of props. ➡️ New object reference = treated as “changed” ➡️ Component re-renders anyway You just paid: 💸 Comparison cost 💸 Render cost 👉 Lose-lose. 📌 Rule of thumb: Profile first → optimize second #ReactJS #Performance #FrontendDev #WebDev
To view or add a comment, sign in
-
🚀 Day 15 of my #100DaysOfCode Challenge! 🚀 Excited to share my latest React project: Book Vibe! 📚 I've been diving deep into front-end development, and this project was a fantastic way to bring multiple concepts together into one polished application. Book Vibe is a fully responsive web app designed to help readers curate their book collections, track what they’ve read, and manage their wishlists. ✨ Key Features: Interactive Curation: Instantly add books to a "Read List" or "Wishlist" with smooth, persistent Toast notifications preventing duplicate entries. Dynamic Sorting: Users can sort their saved books by specific metrics like Number of Pages or Rating. Seamless Navigation: Built a clean tabbed interface to switch between lists without reloading, and a custom 404 error page to catch broken links gracefully. Fully Responsive: Carefully styled to look great on everything from mobile phones to ultra-wide desktop monitors. 🛠️ The Tech Stack: Core: React (v18), Vite Routing & State: React Router DOM (v6 Data Router API), Context API Styling & UI: Tailwind CSS, DaisyUI, React Icons Deployment: Netlify 🧠 Biggest Takeaways & What I Learned: This project pushed me to level up my state management. Moving away from prop drilling and effectively using the Context API made managing the global state of the reading lists across different components so much cleaner. I also gained some serious hands-on experience with deployment routing. Deploying a Single Page Application (SPA) with React Router meant diving into how server-side routing works, and configuring a _redirects file on Netlify to ensure users can refresh or visit direct URLs without hitting those dreaded 404 errors! I would love to hear your thoughts. If you have any feedback on the UI, the code structure, or how I can improve the sorting logic, please drop a comment below! 👇 🔗 Live Demo: [https://lnkd.in/gepCR4Vk] 💻 GitHub Repo: [https://lnkd.in/gN9DbC32] #ReactJS #TailwindCSS #WebDevelopment #Frontend #JavaScript #DaisyUI #ProgrammingHero #SoftwareEngineering #TechJourney
To view or add a comment, sign in
-
Spent 2 days debugging why a dropdown caused 47 re-renders. Turns out I didn't actually understand how React renders. Here's what I learned (Day 2 of my frontend system design series): Most devs think render = DOM update. It doesn't. React rendering is just calling your component function. DOM updates only happen if something actually changed. What triggers a re-render: → State changes (useState / useReducer) → Parent re-renders (children always follow) → Context value updates (all consumers re-render) The fix isn't always React.memo. It's understanding WHY the render happened first. Open the React Profiler. Record. Interact. Stop. It shows exactly which components were rendered and how long each took. Found my bug in 3 minutes. Building in public as I go through GreatFrontend's curriculum — follow along if you're leveling up too. #ReactJS #Frontend #WebDev #JavaScript #SystemDesign
To view or add a comment, sign in
-
-
Junior me: "Why is my React component randomly resetting?" Senior me: "Did you touch the DOM directly?" Junior me: "...maybe" Here's the lesson that took me longer than I'd like to admit: React owns the DOM. You don't. When you do this 👇 document.querySelector('.box').style.display = 'none'; React has no idea. On the next re-render, it overwrites you. Silently. Mercilessly. The right way? ✅ Use useEffect to run side effects after render ✅ Use useRef for safe, controlled DOM access ✅ Use state to drive UI changes — not DOM calls useEffect(() => { inputRef.current.focus(); }, []); This is React-aware. It survives re-renders. It cleans up after itself. The mental shift that changes everything: You're not telling the DOM what to do. You're telling React what the UI should look like. React does the rest. Took me a while to get this. Hope it saves you some debugging hours. 🙌 #React #useEffect #JavaScript #FrontendDevelopment #WebDev #ReactJS #Programming #DeveloperLife #TechTips #CodeNewbie
To view or add a comment, sign in
-
Why does a component re-render even when its state hasn’t changed? Many developers assume that re-rendering only occurs when state changes, but that’s not entirely accurate. Here are the scenarios when React re-renders a component: - Its state changes - Its props change - Its parent re-renders The surprising part is that even if props and state remain the same, if the parent re-renders, the child will also re-render. For example: ```javascript function Parent() { const [count, setCount] = useState(0); return <Child />; } ``` In this case, even though the Child component has no changes, it will still re-render when the Parent updates. This happens because React re-runs the component function to check for any changes. Key Insight: Re-render does not equal DOM update. React may re-render, but it will only update the DOM if something has actually changed. To optimize performance, consider the following strategies: - Use React.memo - Use useMemo / useCallback - Avoid unnecessary parent re-renders #ReactJS #JavaScript #FrontendDevelopment #ReactInternals #SoftwareEngineering #LearningInPublic
To view or add a comment, sign in
-
🚀 Day 32/100 – #100DaysOfCode Today I’m sharing another React project: 🔗 Book Vibe – Book Discovery Platform This project is focused on creating a clean and interactive platform for exploring books and reading-related content. 🔹 Project Idea The main goal is to build a system where users can browse, explore, and interact with books in a structured and user-friendly way. 🔹 Core Features - Display books dynamically from data - Explore book details (title, author, etc.) - Smooth navigation between pages - Responsive and clean UI 🔹 Core Concepts Used - Dynamic Data Rendering → Showing book data using .map() - Routing & Navigation → Moving between pages without reload - State Management → Handling user interactions and UI updates - Component-Based Design → Breaking UI into reusable parts - Recharts → Beautiful visual chart activity 🔹 What This Project Demonstrates - How to build a content-based application - Managing and displaying structured data - Creating a smooth user experience with React Live Link: https://lnkd.in/gYxJsuT4 Don't forget to share your thoughts in the comments below! 32 days down, 68 more to go.| | #Day32 #100DaysOfCode #ReactJS #WebDevelopment #FrontendDevelopment #JavaScript #Projects
To view or add a comment, sign in
-
Most React performance advice is wrong. Not because the patterns are bad but because developers apply them without understanding what React is actually doing. Here’s what I’ve learned: React.memo without useCallback is just theater. memo tells React: “Only re-render if prop references change.” But if you pass a new function reference on every render, memo does absolutely nothing. // ❌ Kills memo on every render <ProductCard onSelect={(id) => handleSelect(id)} /> // ✅ Actually works const handleSelect = useCallback((id) => { dispatch({ type: "SELECT", payload: id }); }, [dispatch]); useMemo has a cost use it surgically. React still performs dependency comparison on every render. For cheap computations, the memoization overhead can be higher than simply recalculating. Use useMemo only when: the computation is genuinely expensive the result is passed to a memoized child you’ve measured it, not assumed it Before reaching for memo or useMemo, ask: What is actually triggering the re-render? Can you eliminate the trigger instead of memoizing around it? Structural state changes beat memoization every time. What’s the nastiest React performance bug you’ve hit in production? #React #ReactJS #Frontend #TypeScript #WebDevelopment #MERN #JavaScript #SoftwareEngineering
To view or add a comment, sign in
-
🧠 React Doesn’t Re-render Because State Changed We’ve all heard this: “React re-renders when state changes.” Sounds correct. But it’s not the full truth. 🔍 What actually triggers a re-render? React re-renders when: 👉 You call a state setter (setState) Not when the value “changes”. Example const [count, setCount] = useState(0); setCount(0); Even though the value is the same… 👉 React may still schedule a render. Why? Because React doesn’t first check: “Did the value change?” It reacts to: “Did you ask for an update?” 🧠 So what happens next? React does a quick comparison (Object.is) If the value is the same: 👉 It bails out and skips unnecessary DOM updates But the render phase can still happen. 🎯 Why this matters This explains why: Your component “renders” but UI doesn’t change Memoization sometimes feels inconsistent Performance issues appear in unexpected places 💥 The Real Mental Model React doesn’t track changes. It responds to update requests. 🧠 Senior Insight Optimizing React is not about “reducing state changes” It’s about 👉 reducing unnecessary updates #ReactJS #FrontendDevelopment #JavaScript #ReactInternals #WebPerformance #CleanCode #LearningInPublic
To view or add a comment, sign in
-
For a long time, I tried to stop React from re-rendering. Turns out, I was solving the wrong problem. React is already fast at rendering. The real issue isn’t re-renders—it’s 𝐰𝐡𝐚𝐭 𝐲𝐨𝐮 𝐝𝐨 𝐝𝐮𝐫𝐢𝐧𝐠 𝐞𝐚𝐜𝐡 𝐫𝐞𝐧𝐝𝐞𝐫. If your component runs expensive logic every time it renders, performance will suffer no matter how many optimizations you add. A simple example: const sortedUsers = users.sort((a, b) => a.age - b.age) This runs on every render. A better approach: const sortedUsers = useMemo( () => users.slice().sort((a, b) => a.age - b.age), [users] ) Now the sorting only happens when `users` actually change. This small shift changed how I think about performance. The goal is not fewer renders—it’s 𝐥𝐞𝐬𝐬 𝐰𝐨𝐫𝐤 𝐩𝐞𝐫 𝐫𝐞𝐧𝐝𝐞𝐫. Once you focus on that, tools like `useMemo` and `useCallback` start making sense instead of being overused blindly. 💡 Here’s what I apply in real projects: ✔️ Avoid heavy computations directly inside render ✔️ Use `useMemo` only for expensive operations ✔️ Measure before optimizing—don’t guess React performance isn’t about tricks. It’s about understanding where the real cost is. 💬 𝐖𝐡𝐞𝐧 𝐝𝐢𝐝 𝐑𝐞𝐚𝐜𝐭 𝐩𝐞𝐫𝐟𝐨𝐫𝐦𝐚𝐧𝐜𝐞 𝐟𝐢𝐧𝐚𝐥𝐥𝐲 “𝐜𝐥𝐢𝐜𝐤” 𝐟𝐨𝐫 𝐲𝐨𝐮? 👉 Follow Usman Ahmed for more Updates! #ReactJS #FrontendEngineering #WebPerformance #JavaScript #CleanCode #SoftwareEngineering #ReactHooks
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