How I Understood ActivityHook in React(Activity Hook) One day I built a simple toggle in React: 👉 Switch between Home and User Form At first, I wrote it the usual way: </>Jsx {showHome ? <Home /> : <UserForm />} And it worked. But there was a problem. Every time I switched: • Form inputs got cleared 😩 • State was lost • Everything reset 🧠 Before (without Activity) React thinks like this: 👉 “Remove one component, mount the other.” So switching means: • Destroy → Create again • State = gone 💡 Then I discovered Activity </>Jsx import { useState, Activity } from "react"; export default function App() { const [showHome, setShowHome] = useState(true); return ( <> <button onClick={() => setShowHome(true)}>Home</button> <button onClick={() => setShowHome(false)}>User Form</button> <Activity mode={showHome ? "visible" : "hidden"}> <Home /> </Activity> <Activity mode={!showHome ? "visible" : "hidden"}> <UserForm /> </Activity> </> ); } 🧠 After (with Activity) React now thinks like this: 👉 “Keep both components alive… just hide one.” So switching means: • No unmount • No reset • State stays intact ✅ 🔥 Real-life example It’s like switching tabs on your phone: • App doesn’t close • It just goes to background 💡 The lesson I learned Before: 👉 Render vs Unmount After: 👉 Visible vs Hidden That small shift changed everything. Now I don’t ask: 👉 “Should I render this?” I ask: 👉 “Should I keep it alive?” Still learning React the human way. 🚀 #JavaScript #FrontendDevelopment #LearningInPublic #CleanCode #ReactJS #useEffect #useMemo #useCallback #FrontendDevelopment #LearningInPublic #JavaScript #WebDevelopment #DeveloperJourney #ReactHook #React19 #ActivityHook
React Activity Hook: Preserve State and Avoid Unmounting
More Relevant Posts
-
🔁 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
-
-
🟦 What is TypeScript? TypeScript is JavaScript with safety built in. It adds types to your code so you can catch mistakes before the app runs. 🟩 JavaScript vs TypeScript 👉 JavaScript = flexible 👉 TypeScript = flexible + safe 🧠 Why Developers Use It JavaScript is powerful, but in large apps it can get too loose. TypeScript helps you write code that is clearer, safer, and easier to scale. ⚡ JavaScript Example js function login(user) { return user.name.toUpperCase(); } 💥 If user.name is missing, the app can crash at runtime. ✅ TypeScript Example ts interface User { name: string; } function login(user: User) { return user.name.toUpperCase(); } 💡 TypeScript checks the structure early, so fewer bugs reach production. 🔍 JavaScript vs TypeScript — Simple View ⏱️ When Should You Use TypeScript? Large applications Team projects APIs and backend systems Long-term production code ❌ Skip it for: Small scripts Quick experiments Temporary testing 🌍 Where TypeScript Is Used ⚛️ React apps 🅰️ Angular apps 🟢 Vue apps 🖥️ Node.js backends 📱 React Native apps ⚙️ Real-World Example Imagine an API returns user data: ts interface User { id: number; name: string; } async function getUser(): Promise<User> { const res = await fetch("/api"); return res.json(); } 💡 If the API sends the wrong data, TypeScript can warn you early — before the UI breaks. 💙 Benefits of TypeScript Fewer bugs Cleaner code Better autocomplete Easier teamwork Better scalability 🔥 Final Thought TypeScript doesn’t replace JavaScript. It makes JavaScript safer, cleaner, and production-ready. 💬 Your Turn Are you using TypeScript in your projects, or do you still prefer JavaScript? 🔗 Connect with Me 🔵 LinkedIn: https://lnkd.in/dsTzapEZ ⚫ GitHub: https://lnkd.in/e9nhGyPj 🟣 Portfolio: https://lnkd.in/dXkTmEje ✉️ Email: irshadsaeed6363@gmail.com 📱 WhatsApp: +966 536805306 #TypeScript #JavaScript #WebDevelopment #FrontendDevelopment #ReactJS #Angular #VueJS #NodeJS #Programming #Developers #CleanCode #SoftwareEngineering #TechCommunity #LearnToCode #SaudiDevelopers
To view or add a comment, sign in
-
-
React 19 just solved one of the most annoying problems in frontend development. Every React developer has hit this before. You hide a sidebar. The user opens it again. The scroll position is gone. The form fields are cleared. The state has completely reset. You have to rebuild the experience from scratch every time the component mounts. Before React 19, this was the default behavior. When you wrote {isVisible && <Sidebar />}, React unmounted the component when isVisible became false. Every piece of state inside it was destroyed. Effects stopped. Inputs cleared. Scroll position lost. React 19 introduces the Activity component and it changes this completely. import { Activity } from "react"; <Activity mode={isVisible ? "visible" : "hidden"}> <Sidebar /> </Activity> Now when you hide the sidebar: -> State is saved in the background -> Effects pause instead of stopping completely -> Scroll position is preserved -> When it comes back, it restores instantly React hides the component but keeps its state in memory. This matters most for: -> Tab switching where each tab has its own state -> Sidebars and drawers that open and close frequently -> Multi-step forms where going back should restore inputs -> Any component where destroying state creates a bad user experience One small API change. Significantly better user experience with almost no extra code. Are you already on React 19 or still migrating? #React #React19 #FrontendDevelopment #JavaScript #WebDevelopment #Developers #UIEngineering
To view or add a comment, sign in
-
-
🚀 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
To view or add a comment, sign in
-
-
Day 19: Custom Hooks in React If you want to write clean, reusable, and professional React code, you must understand Custom Hooks. 📌 What is a Custom Hook? A Custom Hook is a JavaScript function that starts with use and allows you to reuse React logic (state + effects) across multiple components. 👉 Example: useFetch, useAuth, useLocalStorage 📌 Why Custom Hooks are useful? Without custom hooks, we often repeat the same logic again and again ❌ Custom hooks help us: ✅ Reuse logic ✅ Keep components clean ✅ Reduce duplicate code ✅ Improve maintainability 📌 Example: Custom Hook (useCounter) import { useState } from "react"; function useCounter(initialValue = 0) { const [count, setCount] = useState(initialValue); const increase = () => setCount(prev => prev + 1); const decrease = () => setCount(prev => prev - 1); const reset = () => setCount(initialValue); return { count, increase, decrease, reset }; } export default useCounter; 📌 Using the Custom Hook import useCounter from "./useCounter"; function CounterApp() { const { count, increase, decrease, reset } = useCounter(5); return ( <div> <h1>{count}</h1> <button onClick={increase}>+</button> <button onClick={decrease}>-</button> <button onClick={reset}>Reset</button> </div> ); } 📌 Key Point Custom Hooks do not return JSX. They return logic (state + functions). 📌 Real-world Use Cases 🔥 Authentication Hook (useAuth) 🔥 API Fetch Hook (useFetch) 🔥 Theme Hook (useTheme) 🔥 LocalStorage Hook (useLocalStorage) #ReactJS #CustomHooks #FrontendDevelopment #JavaScript #WebDevelopment #LearnInPublic #CodingJourney
To view or add a comment, sign in
-
Stop building "Spaghetti" React projects. 🍝 We’ve all been there. You start a project, it’s clean. 3 months later, your components folder has 87 files, and you can't find where the API logic lives. In 2026, "Senior" doesn't mean you write better code—it means you build better Architectures. Here is the Clean Architecture folder structure I use for scalable React apps. The "Feature-First" Structure 📂 Stop grouping by "type" (all components in one folder). Group by Feature. src/ ├── assets/ # Images, fonts, global icons ├── components/ # Global shared UI (Buttons, Inputs, Modals) ├── config/ # API keys, constants, environment setup ├── features/ # THE CORE: Folder per business feature │ ├── auth/ # Login, Signup, ForgotPassword logic │ │ ├── api/ # Auth-specific API calls │ │ ├── components/ │ │ ├── hooks/ │ │ └── types/ │ ├── dashboard/ # Charts, Stats, User Data │ └── profile/ # Settings, UserAvatar ├── hooks/ # Global reusable hooks (useDebounce, useTheme) ├── lib/ # Third-party configs (Axios, React Query, Firebase) ├── providers/ # Context Providers (Theme, Auth, QueryClient) ├── services/ # Global API services or utilities └── types/ # Global TypeScript interfaces Why this wins in 2026: Isolation: If you need to delete the "Auth" feature, you just delete one folder. No hunting for files across the whole project. AI-Friendly: Tools like Cursor or Claude work 10x better when they have a clear "Feature Context." It prevents them from hallucinating where a file should go. Scalability: This works whether you have 5 components or 500. New developers can find exactly what they need in seconds. Testing: You can keep your .test.ts files right inside the feature folder. Pro-Tip: Every feature folder should have an index.ts (Barrel file) that exports only what the rest of the app needs. This keeps your imports clean. #ReactJS #SoftwareArchitecture #CleanCode #WebDevelopment #JavaScript #Frontend #CodingTips #TechTrends2026 #ProductEngineering
To view or add a comment, sign in
-
Most React developers can use hooks. But very few can explain how React actually works. Let’s test that 👇 As a React.js developer, how many of these can you explain clearly? 1. Fiber Architecture 2. Concurrent Rendering 3. Suspense for Data Fetching 4. useEffect vs useLayoutEffect 5. Hydration 6. useTransition 7. flushSync & Deferred Updates 8. Error Boundaries 9. React.memo vs useMemo vs useCallback 10. Context Re-renders --- Be honest: If you struggle to explain more than 5 of these… you’re not alone. But this is exactly the gap between: 👉 writing React code 👉 and truly understanding React --- Senior engineers don’t just build features. They understand: • why re-renders happen • how scheduling works • where performance breaks --- So… what’s your score? And which one do you want to master next? #reactjs #frontend #webdevelopment #javascript #softwareengineering
To view or add a comment, sign in
-
-
𝐓𝐫𝐢𝐜𝐤𝐲 𝐑𝐞𝐚𝐜𝐭 𝐂𝐥𝐨𝐬𝐮𝐫𝐞 𝐈𝐧𝐭𝐞𝐫𝐯𝐢𝐞𝐰 𝐐𝐮𝐞𝐬𝐭𝐢𝐨𝐧 🤔 Many developers understand closures in JavaScript… but get confused when it comes to React. Question: What will be the output of this code? Example 👇 import React, { useState } from "react"; export default function App() { const [count, setCount] = useState(0); const handleClick = () => { setTimeout(() => { console.log(count); }, 1000); }; return ( <> Click </> ); } Now imagine: You click the button 3 times quickly and count updates each time What will be logged after 1 second? Answer 👇 It will log the SAME value multiple times ❌ Why? Because of closure. The setTimeout callback captures the value of count at the time handleClick was created. This is called a “stale closure”. Correct approach ✅ setTimeout(() => { setCount(prev => { console.log(prev); return prev; }); }, 1000); Or use useRef for latest value. Tip for Interview ⚠️ Closures + async code can lead to stale state bugs in React. Good developers know closures. Great developers know how closures behave in React. #ReactJS #JavaScript #Closures #FrontendDeveloper #WebDevelopment #ReactInterview #CodingInterview #ReactHooks
To view or add a comment, sign in
-
I inherited a React codebase once where everything was in Redux. And I mean everything. Dropdown open or closed. Tooltip visible or hidden. Which tab was active on a product detail page. All of it sitting in the global store, all of it with actions and reducers and selectors written for it. The store had grown to the point where a junior developer could not add a simple filter toggle without touching five files. A bug in the cart was causing unrelated product listing components to re-render. Nobody could explain why because tracing state changes through that store took longer than fixing the actual bug. We did a state audit before touching a single line of feature code. The rule we established was straightforward. If only one component needs it, it lives in that component. If a few related components need it, Context API. If it genuinely belongs to the whole application, it goes in Redux. We moved about 60 percent of the store into local component state over two sprints. The Redux store shrank to what it was always supposed to hold cart contents, user session, and payment state. Re-render counts dropped. The codebase became navigable again. New developers stopped needing a guided tour just to add a UI interaction. The real problem was never Redux. Redux is a fine tool. The problem was that the team ha treated global state as the default instead of the last resort. Twelve years in I still see this pattern on almost every React project I join. The store is a junk drawer and everyone knows it and nobody has time to clean it up. Make time. It compounds fast in the wrong direction. What is sitting in your Redux store right now that has no business being there? #ReactJS #Redux #Frontend #SoftwareEngineering #WebDevelopment #JavaScript #CodeQuality #TechLeadership Lakshya Technologies Robert Half Randstad Beacon Hill Google Cloud Security
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