DEV Community

Cover image for <Activity /> component - A Better Way to Hide Components Without Losing State
Madhuban Khatri
Madhuban Khatri

Posted on

<Activity /> component - A Better Way to Hide Components Without Losing State

What is the use of Activity Component?

We can hide the components without losing their state.

What problem it resolve?

Most developers use Conditional Rendering for component hiding. When a component disappears, React completely unmounts it. This means:

  • State is lost
  • Effects are destroyed
  • Form inputs reset
  • Scroll positions disappear
  • Expensive components re-render again later
{visible && <Test/>}
Enter fullscreen mode Exit fullscreen mode

How to use it?

Test.jsx

import React, { useState } from 'react'

function Test() {
    const [count, setCount] = useState(0);

  return (
    <div>
      <h1>{count}</h1>
      <button onClick={()=>setCount(count+1)}>Increment</button>
      <button onClick={()=>setCount(count-1)}>Decrement</button>
    </div>
  )
}

export default Test
Enter fullscreen mode Exit fullscreen mode

App.jsx

import { Activity, useState } from "react"
import Test from "./Test"

function App() {
  const [visible, setVisible] = useState("visible");

  return (
    <>
    <Activity mode={visible=="visible" ? "visible": "hidden"}>
      <Test/>
    </Activity>
    <button onClick={()=>setVisible("visible")}>Visible</button>
    <button onClick={()=>setVisible("hidden")}>Hide</button>
    </>
  )
}

export default App
Enter fullscreen mode Exit fullscreen mode

What happens internally?

When the mode becomes "hidden", state is preserved, and when mode becomes "visible" again, previous state is restored.

Thank you for visiting,
If you have any question then comment below.

Top comments (0)