🚀 React useEffect Lifecycle Made Simple – Mount, Update & Unmount 🧩 Example: User Profile Component import React, { useState, useEffect } from "react"; function UserProfile() { const [userId, setUserId] = useState(1); const [userName, setUserName] = useState(""); useEffect(() => { console.log("Component Mounted or userId changed"); // Simulate fetching user data const fakeFetch = setTimeout(() => { setUserName("User " + userId); console.log("Fetched data for user", userId); }, 500); // Cleanup on unmount or before next effect return () => { clearTimeout(fakeFetch); console.log("Cleanup: Component Unmounted or userId changed"); }; }, [userId]); return ( <div style={{ border: "1px solid #ccc", padding: "1rem", margin: "1rem" }}> <h2>User Profile</h2> <p>User ID: {userId}</p> <p>User Name: {userName}</p> <button onClick={() => setUserId(userId + 1)}>Next User</button> </div> ); } export default UserProfile; 🔹What Happens Step by Step: Mount: - Component appears on screen - useEffect runs → fetches user 1 → updates name - Console: "Component Mounted or userId changed" Update: - Click button → userId changes → component re-renders - useEffect cleanup runs first → old fetch canceled - New fetch runs → updates UI - Console: "Cleanup: Component Unmounted or userId changed" → " Component Mounted or userId changed " Unmount: - Component removed from screen - Cleanup stops any ongoing fetch/timer → prevents memory leaks - Console: "Cleanup: Component Unmounted or userId changed" #ReactJS #JavaScript #Frontend #WebDevelopment #CleanCode #LearningInPublic #Programming
React useEffect Lifecycle Explained: Mount, Update, Unmount
More Relevant Posts
-
🚀 useEffect in React – Side Effects Made Simple ⚡ After learning useState, the next important hook is useEffect. It helps you handle side effects in React. 1️⃣ What is useEffect? 👉 It runs code after the component renders Used for: ✔ API calls ✔ Event listeners ✔ Timers ✔ DOM updates 2️⃣ Basic Example import { useEffect } from "react"; useEffect(() => { console.log("Component rendered"); }); 👉 Runs after every render 3️⃣ Run Only Once (Like componentDidMount) useEffect(() => { console.log("Component mounted"); }, []); 👉 Empty dependency array = run only once 4️⃣ Run When State Changes useEffect(() => { console.log("Count changed"); }, [count]); 👉 Runs only when count changes 5️⃣ Real World Example (API Call) useEffect(() => { fetch("https://lnkd.in/d6JY2AXf") .then(res => res.json()) .then(data => console.log(data)); }, []); 👉 Fetch data when the component loads 6️⃣ Cleanup Function 🧹 useEffect(() => { const timer = setInterval(() => { console.log("Running..."); }, 1000); return () => clearInterval(timer); }, []); 👉 Cleanup runs when component unmounts 7️⃣ Dependency Array Summary ✔ No array → runs every render ✔ [] → runs once ✔ [value] → runs when value changes 🔥 Key Takeaway useEffect = Handle side effects outside UI rendering #React #JavaScript #Frontend #WebDevelopment #LearningByDoing
To view or add a comment, sign in
-
React Folder Structure That Scales 🚀 Most beginners start like this: src/ ├── Home.jsx ├── Navbar.jsx ├── Login.jsx ├── api.js ├── redux.js It works at first. But after adding authentication, APIs, Redux, hooks, layouts, and 20+ pages, finding a file becomes frustrating. That’s why folder structure matters. src/ ├── api/ ├── assets/ ├── components/ │ ├── common/ │ ├── forms/ │ └── ui/ ├── config/ ├── context/ ├── features/ │ ├── auth/ │ ├── dashboard/ │ ├── profile/ │ └── products/ ├── hooks/ ├── layout/ ├── pages/ ├── redux/ ├── routes/ ├── services/ ├── utils/ ├── .env ├── .env.development ├── .env.production └── App.jsx Why this structure? • components/→ Reusable UI • pages/→ Full screens • api/ & services/→ API logic • redux/ → Global state • hooks/ → Reusable logic • routes/ → Clean routing • features/ → Keep each module together For large apps, I prefer feature-based architecture: features/ └── auth/ ├── components/ ├── pages/ ├── hooks/ ├── services/ └── authSlice.js This keeps auth-related files in one place instead of searching through 5 different folders. Best rule: • Small project → Simple structure • Medium project → Organized folders • Large project → Feature-based architecture Clean folder structure = easier debugging + faster development + better teamwork. How do you organize your React projects? #react #reactjs #frontend #webdevelopment #javascript #redux #vite
To view or add a comment, sign in
-
-
𝗡𝗲𝘅𝘁.𝗷𝘀 𝟭𝟱 𝗶𝘀 𝗮 𝗱𝗶𝗳𝗳𝗲𝗿𝗲𝗻𝘁 𝗳𝗿𝗮𝗺𝗲𝘄𝗼𝗿𝗸 𝗻𝗼𝘄. 🚀 If you're still on 14, you're missing a lot. The biggest architecture shift since the App Router. ━━━━━━━━━━ 𝗧𝘂𝗿𝗯𝗼𝗽𝗮𝗰𝗸 — 𝗦𝘁𝗮𝗯𝗹𝗲 & 𝗗𝗲𝗳𝗮𝘂𝗹𝘁 ⚡ Turbopack is now the default bundler. No flags. No config. Just faster. ``` // next.config.ts // That's it. Turbopack is default now. // Want Webpack back? // next dev --webpack ``` Dev server: up to 76% faster cold start. HMR: 5-10x faster refresh. Builds: 2-5x faster compilation. Written in Rust. Incremental by design. Bundles only what's requested. ━━━━━━━━━━ 𝗔𝘀𝘆𝗻𝗰 𝗥𝗲𝗾𝘂𝗲𝘀𝘁 𝗔𝗣𝗜𝘀 — 𝗕𝗿𝗲𝗮𝗸𝗶𝗻𝗴 𝗖𝗵𝗮𝗻𝗴𝗲 🔄 params, searchParams, cookies, headers. All async now. No more sync access. Before: ```tsx export default function Page({ params }) { const { slug } = params; return <h1>{slug}</h1>; } ``` After: ```tsx export default async function Page({ params }) { const { slug } = await params; return <h1>{slug}</h1>; } ``` This unlocks streaming and PPR. Run the codemod: npx @next/codemod upgrade ━━━━━━━━━━ 𝗣𝗮𝗿𝘁𝗶𝗮𝗹 𝗣𝗿𝗲-𝗥𝗲𝗻𝗱𝗲𝗿𝗶𝗻𝗴 (𝗣𝗣𝗥) 🏗️ The biggest idea in Next.js 15. One page. Two rendering modes. Zero compromise. ```tsx import { Suspense } from "react"; export default function Product() { return ( <> {/* Static — cached at build */} <ProductHeader /> {/* Dynamic — streams on request */} <Suspense fallback={<Skeleton />}> <ProductPrice /> </Suspense> </> ); } ``` Static shell loads instantly. Dynamic parts stream in via Suspense. TTFB of static + freshness of dynamic. ━━━━━━━━━━ 𝗖𝗮𝗰𝗵𝗶𝗻𝗴 — 𝗨𝗻𝗰𝗮𝗰𝗵𝗲𝗱 𝗯𝘆 𝗗𝗲𝗳𝗮𝘂𝗹𝘁 🎯 Next.js 14 cached everything. Confused everyone. Next.js 15 caches nothing by default. ```tsx // GET handlers — no longer cached export async function GET() { const data = await fetch("https://api.example.com"); return Response.json(data); } // Opt-in when you need it: export const dynamic = "force-static"; ``` You choose what to cache. Not the framework. ━━━━━━━━━━ 𝗡𝗼𝗱𝗲.𝗷𝘀 𝗠𝗶𝗱𝗱𝗹𝗲𝘄𝗮𝗿𝗲 — 𝗦𝘁𝗮𝗯𝗹𝗲 🔐 Middleware was locked to Edge Runtime. Now it runs full Node.js. ```ts // middleware.ts export const config = { runtime: "nodejs" // Full Node APIs! }; ``` Use fs, crypto, native modules. Real auth flows. No more Edge limitations. ━━━━━━━━━━ 𝗪𝗵𝗮𝘁 𝘁𝗵𝗶𝘀 𝗺𝗲𝗮𝗻𝘀 💡 Turbopack replaces Webpack. Caching is explicit, not magic. PPR blends static and dynamic. Async APIs enable streaming. Next.js 15 is faster, simpler, and honest. The defaults finally make sense. ━━━━━━━━━━ 📌 This is post [2/6] in my Frontend 2026 series. Next: TypeScript 5.6+ — what changed. Have you switched to Turbopack yet? 👇 #nextjs #react #javascript #frontend #webdev #turbopack #programming #webdevelopment #coding #typescript
To view or add a comment, sign in
-
-
🚨 I used index as key in React… …and spent HOURS debugging something that made no sense. Everything looked fine at first. Until I: → deleted an item → reordered the list 💥 Suddenly: ❌ Wrong data was displayed ❌ UI behaved randomly ❌ Bugs I couldn’t explain I kept checking my logic. Turns out… the bug wasn’t my logic. 👉 It was THIS: {data.map((item, index) => ( <div key={index}>{item.name}</div> ))}💡 Problem: React uses keys to track identity. When you use index: → identity = position ❌ → not the actual item So when the list changes… React gets confused 😵 ✅ Fix: {data.map((item) => ( <div key={item.id}>{item.name}</div> ))}👉 Stable key = stable UI 💡 Lesson: If your UI feels “random”… check your keys before your logic. Follow me for more such tips ✍️ 👨💻 #ReactJS #Frontend #JavaScript #SoftwareEngineering
To view or add a comment, sign in
-
-
🚀 Day 12/30 – Conditional Rendering in React Building dynamic UIs based on conditions ⚡ Today’s focus was on Conditional Rendering — a core concept that makes React apps interactive and user-driven. 🔍 What I learned: ✅ Conditional Rendering allows UI to change based on state ✅ React relies on pure JavaScript logic (if, ternary, &&) inside JSX ✅ Essential for real-world features like authentication, loaders, and error handling 💻 Example: function App() { const isLoggedIn = true; return ( <> {isLoggedIn ? <h1>Welcome User</h1> : <h1>Please Login</h1>} </> ); } 🔥 Common Patterns: 1️⃣ Ternary Operator (Most Used) {condition ? <A /> : <B />} 2️⃣ Logical AND (&&) {isLoggedIn && <Dashboard />} 3️⃣ If Statement (Outside JSX) if (!user) return <Login />; 💡 Real-World Use Cases: ✔️ Showing a loader while fetching data ✔️ Displaying error messages ✔️ Rendering dashboard after login ⚡ Advanced Insight: React doesn’t introduce new syntax for conditions — it simply leverages JavaScript inside JSX, making it flexible and powerful. 🔑 Key Takeaway: 👉 Conditional Rendering = Controlling what users see based on application state. 💬 Curious — which approach do you use more: ternary or if/else logic? #React #FrontendDevelopment #JavaScript #WebDevelopment #LearningInPublic
To view or add a comment, sign in
-
-
🚀 Understanding useRef in React — Simplified! Not all data in React should trigger a re-render. 👉 That’s where useRef becomes powerful. 💡 What is useRef? useRef is a hook that lets you store a mutable value that persists across renders—without causing re-renders. ⚙️ Basic Syntax const ref = useRef(initialValue); 👉 Access value using: ref.current 🧠 How it works Value persists across renders Updating it does NOT trigger re-render Works like a mutable container 🔹 Example const countRef = useRef(0); const handleClick = () => { countRef.current += 1; console.log(countRef.current); }; 👉 UI won’t update—but value persists 🧩 Real-world use cases ✔ Accessing DOM elements (focus, scroll) ✔ Storing previous values ✔ Managing timers / intervals ✔ Avoiding unnecessary re-renders 🔥 Best Practices (Most developers miss this!) ✅ Use useRef for non-UI data ✅ Use it for DOM access ✅ Combine with useEffect when needed ❌ Don’t use useRef for UI state ❌ Don’t expect UI updates from it ⚠️ Common Mistake // ❌ Expecting UI update countRef.current += 1; 👉 React won’t re-render 💬 Pro Insight 👉 useRef = Persist value without re-render 👉 useState = Persist value with re-render 📌 Save this post & follow for more deep frontend insights! 📅 Day 14/100 #ReactJS #FrontendDevelopment #JavaScript #ReactHooks #useRef #WebDevelopment #SoftwareEngineering #100DaysOfCode 🚀
To view or add a comment, sign in
-
-
Here is a real-world debugging question asked during a JavaScript/React discussion. import { useEffect, useState } from "react"; export default function App() { const [data, setData] = useState(null); useEffect(() => { fetch("https://lnkd.in/gGnJ7utj") .then((res) => res.json()) .then((result) => { setData(result); console.log("Data:", data); }); }, []); return ( <div> <h1>{data?.title}</h1> </div> ); } ❓ Question: Why does console.log("Data:", data) print null even after calling setData(result)? Think about how React state updates work and when re-renders happen. 💡 Bonus: How would you correctly log the updated data? Drop your answers in the comments 👇 #Debugging #ReactJS #JavaScript #FrontendDevelopment #CodingInterview #ReactHooks #WebDevelopment #Developers
To view or add a comment, sign in
-
⚛️ 𝗜𝗺𝗽𝗿𝗼𝘃𝗶𝗻𝗴 𝗥𝗲𝗮𝗰𝘁 𝗣𝗲𝗿𝗳𝗼𝗿𝗺𝗮𝗻𝗰𝗲 — 𝗨𝘀𝗶𝗻𝗴 𝗖𝗼𝗱𝗲 𝗦𝗽𝗹𝗶𝘁𝘁𝗶𝗻𝗴 As React applications grow, bundle size increases — which directly impacts initial load time. Common problem: • large JS bundle • slow first load • unnecessary code loaded upfront A better production approach is 𝗖𝗼𝗱𝗲 𝗦𝗽𝗹𝗶𝘁𝘁𝗶𝗻𝗴. ❌ 𝗪𝗶𝘁𝗵𝗼𝘂𝘁 𝗖𝗼𝗱𝗲 𝗦𝗽𝗹𝗶𝘁𝘁𝗶𝗻𝗴 𝘪𝘮𝘱𝘰𝘳𝘵 𝘋𝘢𝘴𝘩𝘣𝘰𝘢𝘳𝘥 𝘧𝘳𝘰𝘮 "./𝘋𝘢𝘴𝘩𝘣𝘰𝘢𝘳𝘥"; 𝘪𝘮𝘱𝘰𝘳𝘵 𝘙𝘦𝘱𝘰𝘳𝘵𝘴 𝘧𝘳𝘰𝘮 "./𝘙𝘦𝘱𝘰𝘳𝘵𝘴"; 𝘪𝘮𝘱𝘰𝘳𝘵 𝘚𝘦𝘵𝘵𝘪𝘯𝘨𝘴 𝘧𝘳𝘰𝘮 "./𝘚𝘦𝘵𝘵𝘪𝘯𝘨𝘴"; All components load upfront — even if not used immediately. ❌ 𝗪𝗶𝘁𝗵𝗼𝘂𝘁 𝗖𝗼𝗱𝗲 𝗦𝗽𝗹𝗶𝘁𝘁𝗶𝗻𝗴 𝘪𝘮𝘱𝘰𝘳𝘵 { 𝘭𝘢𝘻𝘺, 𝘚𝘶𝘴𝘱𝘦𝘯𝘴𝘦 } 𝘧𝘳𝘰𝘮 "𝘳𝘦𝘢𝘤𝘵"; 𝘤𝘰𝘯𝘴𝘵 𝘋𝘢𝘴𝘩𝘣𝘰𝘢𝘳𝘥 = 𝘭𝘢𝘻𝘺(() => 𝘪𝘮𝘱𝘰𝘳𝘵("./𝘋𝘢𝘴𝘩𝘣𝘰𝘢𝘳𝘥")); 𝘤𝘰𝘯𝘴𝘵 𝘙𝘦𝘱𝘰𝘳𝘵𝘴 = 𝘭𝘢𝘻𝘺(() => 𝘪𝘮𝘱𝘰𝘳𝘵("./𝘙𝘦𝘱𝘰𝘳𝘵𝘴")); 𝘧𝘶𝘯𝘤𝘵𝘪𝘰𝘯 𝘈𝘱𝘱() { 𝘳𝘦𝘵𝘶𝘳𝘯 ( <𝘚𝘶𝘴𝘱𝘦𝘯𝘴𝘦 𝘧𝘢𝘭𝘭𝘣𝘢𝘤𝘬={<𝘱>𝘓𝘰𝘢𝘥𝘪𝘯𝘨...</𝘱>}> <𝘋𝘢𝘴𝘩𝘣𝘰𝘢𝘳𝘥 /> <𝘙𝘦𝘱𝘰𝘳𝘵𝘴 /> </𝘚𝘶𝘴𝘱𝘦𝘯𝘴𝘦> ); } Now components load 𝗼𝗻𝗹𝘆 𝘄𝗵𝗲𝗻 𝗻𝗲𝗲𝗱𝗲𝗱. 📌 Where this helps most: • large dashboards • admin panels • multi-page apps • heavy third-party libraries 📌 𝗣𝗿𝗼𝗱𝘂𝗰𝘁𝗶𝗼𝗻 𝗕𝗲𝗻𝗲𝗳𝗶𝘁𝘀: • faster initial load • reduced bundle size • better performance • improved user experience 📌 𝗕𝗲𝘀𝘁 𝗣𝗿𝗮𝗰𝘁𝗶𝗰𝗲𝘀: • split at route level • avoid over-splitting • use meaningful fallbacks • monitor bundle size Loading everything at once works — but splitting wisely improves performance significantly. 💬 Curious — do you apply code splitting at route level or component level? #ReactJS #CodeSplitting #Performance #FrontendDevelopment #JavaScript #WebDevelopment #SoftwareEngineering #Optimization
To view or add a comment, sign in
-
Most developers reach for an array by default. But sometimes, that's the wrong tool. When you use array.find() to look up a value, it scans from the start every single time. That's O(n) time complexity. With 10 items, unnoticeable. With 10,000 items, your server feels it. A Map object solves this. Instead of this: const user = users.find(u => u.id === id) Do this: const userMap = new Map(users.map(u => [u.id, u])) const user = userMap.get(id) Map lookups are O(1). It doesn't matter if you have 10 items or 10 million, the lookup time stays the same. This only makes sense when you have a fixed dataset and are doing repeated lookups. If you're looking up once, array.find() is perfectly fine. But if you're hitting that array multiple times, consider reaching for a Map instead. #JavaScript #NodeJS #SoftwareEngineering #WebDevelopment #Performance
To view or add a comment, sign in
-
-
Hook: We need to talk about the awkward phase between useState and installing Redux. For a long time, I defaulted to useState for literally everything. Then you hit a feature—like a complex multi-step form or a data-heavy dashboard—and suddenly your component has six different state setters. Your event handlers turn into a tangled mess of setLoading(false), setData(res), and setError(null), all firing at once and risking race conditions. That’s exactly when useReducer goes from being "that confusing React hook" to the most vital tool for clean architecture. ✅ When you SHOULD use it: Dependent State: When updating one piece of state requires changing another at the exact same time (e.g., resolving an API call updates loading, data, and error simultaneously). Complex Objects: When your state is a deeply nested object or array that requires precise mapping or filtering on every update. Centralizing Logic: When you want to pull messy update logic out of your UI component and into a pure, highly testable JavaScript function. You can unit-test a reducer without ever touching a React component. ❌ When you SHOULD NOT use it: Simple Primitives: Please don't write a 15-line reducer with action types and switch statements just to toggle a modal open and closed. useState is perfectly fine for isolated, flat values. Just to look "advanced": The boilerplate is real. If the state is simple, keep the code simple. Don't frustrate the next developer who reads your code just to flex a hook. 💡 Why it matters in production: At the product-company level, you don't always need Redux, Zustand, or MobX for every feature. Pairing useReducer with the Context API gives you a powerful, localized global state. You can pass the dispatch function down the tree, completely avoiding prop-drilling without bloating your bundle size with third-party dependencies. It takes a minute to shift your brain from "updating values" to "dispatching actions," but your future self (and your teammates) will thank you when debugging. What is your personal threshold for making the switch from useState to useReducer? Let's debate below. #ReactJS #FrontendEngineering #SoftwareArchitecture #CleanCode #JavaScript
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