React Activity Hook: Preserve State and Avoid Unmounting

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

  • graphical user interface

To view or add a comment, sign in

Explore content categories