Day 13: Component Lifecycle in React (Using Hooks) Before Hooks, React had lifecycle methods in class components. Now, with Hooks, we can handle the entire lifecycle using useEffect. 📌 What is Component Lifecycle? Every React component goes through 3 main phases: 1️⃣ Mounting → Component is created and added to the DOM 2️⃣ Updating → Component re-renders when state/props change 3️⃣ Unmounting → Component is removed from the DOM 📌 Handling Lifecycle with useEffect 👉 1. Mounting (Component Did Mount) useEffect(() => { console.log("Component Mounted"); }, []); Runs only once when the component loads. 👉 2. Updating (Component Did Update) useEffect(() => { console.log("Component Updated"); }, [count]); Runs whenever count changes. 👉 3. Unmounting (Component Will Unmount) useEffect(() => { return () => { console.log("Component Unmounted"); }; }, []); Used for cleanup (like clearing timers, removing listeners). 📌 Real-world Example Think of a timer app • Start timer → Mount • Update time → Update • Stop/leave page → Unmount 📌 Why Lifecycle is Important ✅ Prevent memory leaks ✅ Manage API calls properly ✅ Control when code runs ✅ Optimize performance #ReactJS #FrontendDevelopment #JavaScript #WebDevelopment #CodingJourney #LearnInPublic
React Component Lifecycle with Hooks: Mounting, Updating, Unmounting
More Relevant Posts
-
Your Webpack Module Federation setup works perfectly in development. Five micro frontends, all loading seamlessly. Then you check the Network tab. Five copies of React. Five copies of ReactDOM. Five copies of React Router. 2.5MB of duplicated JavaScript the browser downloads, parses, and executes for zero reason. But the real problem is not performance. It is this error: "Invalid hook call. You might have more than one copy of React in the same app." Two React instances = two hook registries. A component rendered by React #1 cannot call hooks from React #2. Your entire app crashes. The fix: Module Federation's shared config with the singleton pattern. Here's what I cover in the full guide: 1. Why sharing dependencies cuts bundle size by 57% (real numbers) 2. What singleton: true actually does at runtime (step-by-step) 3. requiredVersion vs strictVersion vs eager - when to use each 4. Why the host shares more dependencies than remotes 5. React vs Next.js shared config differences (eager: false matters) 6. What you should share (React, Redux) vs what you should NOT (lodash, date-fns) 7. How to debug shared deps with __webpack_share_scopes__ in DevTools Every code example is from a production micro frontend monorepo with multiple remotes. Read the full guide: https://lnkd.in/ggcubTC5 #MicroFrontend #ModuleFederation #Webpack5 #ReactJS #JavaScript #WebDev #FrontendArchitecture #SingletonPattern #WebPerformance #Monorepo #SrinuDesetti
To view or add a comment, sign in
-
-
How I Learned to Optimize 100k+ Items in React One day I built a simple list in React. Everything was fine… until I loaded 100,000+ items 😅 Suddenly: • UI became slow • Scrolling lagged • My laptop fan started acting like a jet engine ✈️ I thought: 👉 “React is slow.” But I was wrong. 🧠 Then I asked a better question 👉 Do users really need to see 100,000 items at once? The answer was obvious: ❌ No. Users only see what’s on the screen. 💡 That’s when it clicked Instead of rendering everything, I should render only visible items. This concept is called: 👉 Virtualization 🧠 Human version of this Imagine a long book 📖 You don’t read all pages at once. You only read the current page. Same idea. 🚀 What I changed Instead of: ❌ Rendering 100k items I did: ✅ Render only 20–30 visible items ✅ Load more as user scrolls 🔧 Tools that helped me • react-window • react-virtualized These libraries handle everything smartly. ⚡ Extra optimizations I learned • Use useMemo for heavy calculations • Use useCallback for stable functions • Avoid unnecessary re-renders • Keep components lightweight 💡 The biggest lesson Performance is not about doing more. It’s about doing less… smartly. Now whenever my app slows down, I ask: 👉 Am I rendering more than needed? Still learning React the human way. 🚀 #JavaScript #FrontendDevelopment #LearningInPublic #CleanCode #ReactJS #FrontendDevelopment #LearningInPublic #JavaScript #WebDevelopment #DeveloperJourney #ReactHook #Performance
To view or add a comment, sign in
-
-
Headline: 📈 Small Projects, Big Progress. From static HTML pages to dynamic, state-driven interfaces. This To-Do app was a fun way to practice Clean Code principles in Vanilla JS. Key Features: ✅ Add tasks via button or keyboard. ✅ Individual task deletion. ✅ Clean, centered UI for better focus. Next step? Adding LocalStorage so the tasks persist even after a page refresh! 🔄 #LearnToCode #JavaScript #DeveloperJourney #WebDev #PortfolioProject
To view or add a comment, sign in
-
There's a page in the React docs called "You Might Not Need an Effect." I'd say it's one of the most important pages in the entire React documentation. And most developers have either never read it or read it once and moved on. The whole idea comes down to one question: is your code syncing React with something React doesn't control? A WebSocket, a browser API, a third-party library? If yes, useEffect makes sense. If no, you're probably just adding extra renders and making your code harder to follow. Some patterns worth knowing: If you're deriving a value from props or state, just calculate it during render. No state, no effect needed. If you're responding to a user action like a click or form submit, put it in the event handler. The event handler already knows what happened. The effect doesn't. If you need to reset state when a prop changes, use the key prop. React will remount the component and reset everything automatically. If you're chaining effects where one sets state and triggers another, collapse all of it into a single event handler. React batches those updates into one render. If a child is fetching data just to pass it up to a parent, flip the flow. Let the parent fetch and pass it down. The rule the docs give is honestly the clearest way I've seen it put: if something runs because the user did something, it belongs in an event handler. If it runs because the component appeared on screen, it belongs in an effect. Every unnecessary useEffect is an extra render pass, an extra place for bugs to hide, and more code for the next person to untangle. Worth a read if you haven't: https://lnkd.in/gqUr7e_S How many effects in your current codebase do you think would actually pass that test? #ReactJS #Frontend #JavaScript #WebDevelopment #CleanCode
To view or add a comment, sign in
-
Have you ever needed to touch the DOM directly while working in React? React is designed to be declarative. You describe the UI based on state, and the library handles the updates. But occasionally, you need what we call an 'escape hatch.' This is precisely where 'refs' come into play. They provide a way to access a DOM node or a React element directly, bypassing the standard re-render cycle. The most common reason to reach for a ref is to manage things like focus, text selection, or media playback. If you need a specific input field to focus the moment a page loads, you cannot easily do that with state alone. You need to reach into the DOM and call the native '.focus()' method. Beyond the DOM, refs are also perfect for storing any mutable value that needs to persist across renders without triggering a UI update. This includes things like timer IDs or tracking previous state values for comparison. However, with great power comes responsibility. Using refs is essentially stepping outside of the React ecosystem and taking manual control. If you can achieve your goal using props and state, you should. Overusing refs can make your components harder to debug and breaks the predictable flow of data that makes React so reliable. It is a tool for the edge cases, not the daily routine. Use it when you need to talk to the browser directly, but keep your core logic declarative. #ReactJS #SoftwareEngineering #WebDevelopment #Javascript #Frontend #CodingTips
To view or add a comment, sign in
-
🚀 Repeating your layout in every React page? I faced this problem too. When I started using React Router, my code looked like this: 👉 Same Navbar in every page 👉 Same Sidebar everywhere 👉 Layout repeated again & again 😬 It worked… but it was messy and hard to maintain. 💡 The Problem: Without using Outlet 👇 ❌ Repeated layout code in every component ❌ Hard to update UI (change one → update all) ❌ Not scalable for large apps 💡 The Fix: Use Outlet 👉 import { Outlet } from "react-router-dom"; 💡 Solution Example: function Layout() { return ( <div> <Navbar /> <Outlet /> </div> ); } 👉 Now all pages render inside <Outlet /> 🎯 💡 Before vs After: ❌ Before: Every page = Navbar + Content + Footer 😓 ✅ After: Layout handles UI Outlet handles page content 🚀 💡 Why it matters: ✔ No more duplicate code ✔ Easy to maintain ✔ Clean project structure ✔ Perfect for dashboards & large apps 🔥 Pro tip: If you're repeating layouts — you're missing Outlet. 🔥 Lesson: Smart developers don’t repeat UI — they structure it. Are you still repeating layouts or using Outlet the right way? 👀 #React #ReactRouter #WebDevelopment #Frontend #CodingTips #JavaScript
To view or add a comment, sign in
-
-
🧠 Why Inline Functions Can Hurt React Performance This looks totally fine 👇 <button onClick={() => handleClick(id)}> Click </button> Works? ✅ Clean? ✅ Optimized? ❌ 🔍 What’s actually happening Every render creates a new function instance. () => handleClick(id) // new function every time So React sees: 👉 “This prop changed” Even if nothing else changed. ⚠️ The hidden impact When passed to child components: <Child onClick={() => handleClick(id)} /> 👉 Child re-renders every time 👉 React.memo becomes useless 👉 Performance drops in large apps ✅ Better approach const handleItemClick = useCallback(() => { handleClick(id); }, [id]); <Child onClick={handleItemClick} /> Now: ✔ Stable reference ✔ Fewer re-renders ✔ Better performance 🎯 Real Insight React doesn’t compare function logic. It compares references. 💥 Senior takeaway Most performance issues are not from big logic. They come from small patterns repeated many times. #ReactJS #FrontendDeveloper #JavaScript #WebDevelopment #Performance #SoftwareEngineering #CodingTips #TechCareers
To view or add a comment, sign in
-
🚀 Understanding `useState` & `useEffect` in React If you're working with React, these two hooks are must-know fundamentals: 🔹 **useState** * Used to create and manage state inside a functional component * Returns a state value and a setter function * Triggers re-render when state changes Example: ```js const [count, setCount] = useState(0); ``` 🔹 **useEffect** * Used for side effects (API calls, subscriptions, DOM updates) * Runs after the component renders * Can depend on state or props Example: ```js useEffect(() => { console.log("Component mounted or count changed"); }, [count]); ``` 💡 **Why `useState` should be declared before `useEffect`?** React hooks follow a strict rule: 👉 Hooks must be called in the same order on every render. Since `useEffect` often depends on state values, defining `useState` first ensures: * State is initialized before being used * Dependencies inside `useEffect` are available * Hook order remains consistent (avoiding bugs or crashes) ⚠️ Breaking hook order can lead to unexpected behavior and hard-to-debug issues. ✅ Always follow: 1. Declare state (`useState`) 2. Then handle side effects (`useEffect`) --- Mastering these basics makes your React apps more predictable and maintainable 💻✨ #React #JavaScript #WebDevelopment #Frontend #Programming #ReactHooks
To view or add a comment, sign in
-
Next.js 15 is out — and it changes more than you think. ⚡ I've been digging into everything that shipped. Here's what actually matters for your day-to-day development: ① Turbopack is finally stable The Rust-based bundler is now production-ready. Local dev server is up to 5x faster than Webpack. Cold starts? Almost instant. This alone is worth upgrading for. ② Async Request APIs — breaking change alert cookies(), headers(), and route params are now async. You must await them. If you're upgrading an existing app, audit every usage. It's a small change with a big blast radius. ③ Partial Prerendering (PPR) The most exciting architectural feature in years. Static HTML shell renders instantly. Dynamic content streams in behind it. You get the speed of static AND the freshness of dynamic — in one page. ④ next/after — post-response logic Ever wanted to run analytics or cleanup AFTER sending a response? next/after makes this a first-class feature. No more hacks, no more background job workarounds. ⑤ React 19 ships built-in Actions, use(), useOptimistic, and the React Compiler — all supported out of the box. Next.js 15 + React 19 together is the most powerful the stack has ever been. ⑥ Caching is now explicit fetch() responses are no longer cached by default. This was one of the most confusing parts of Next.js 13/14. Now you opt into caching intentionally. Your app does exactly what you tell it to. The theme across all of it? Next.js 15 removes the magic and gives you control. Less surprises. More predictability. Faster iteration. If you haven't upgraded yet — start with a new project. The DX difference is immediately noticeable. 💬 Have you tried Next.js 15 yet? What feature are you most excited about? #NextJS15 #NextJS #React #Frontend #WebDevelopment #JavaScript #Programming #WebDev #SoftwareEngineering #TechTips
To view or add a comment, sign in
-
-
Built a real DOM-based project today......a To-Do List And honestly, it taught me more than I expected. Here’s what it does: - You can type a task and add it using a button - Or simply press Enter on the keyboard to add it instantly - Each task gets added dynamically to the list - Task counters update in real time (In Progress + Completed) - You can delete tasks anytime - You can also mark tasks as completed and track progress What seemed like a “simple project” actually pushed me to understand how everything connects behind the scenes: - How DOM updates work in real time - How events like clicks and keyboard inputs interact with JavaScript - How dynamic UI changes without refreshing the page Even a basic To-Do app contains the core logic of real-world applications. Small steps. Real understanding. Constant building. 💻🔥 #WebDevelopment #JavaScript #DOM #FrontendDevelopment #BuildInPublic
To view or add a comment, sign in
Explore related topics
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