DEV Community

Simone Gentili
Simone Gentili

Posted on

React <Activity /> component

<Activity /> component

Today I was wondering in new React 19.2 features. For example I have been play with <Activity /> one. Here an example. The example is complete but I'll write few considerations about how to use it.

import { Activity, useState } from 'react'
import './App.css'

function App() {
  const [mode, setMode] = useState(true)
  return (
    <>
      <button onClick={() => setMode(!mode)}>
        toggle
      </button>

      <Activity mode={mode === true ? 'hidden' : 'visible'}>
        <textarea placeholder="Type something..." rows={4} cols={50} />
      </Activity>
    </>
  )
}

export default App
Enter fullscreen mode Exit fullscreen mode

The old way

I think is good component. It makes more readable and with more features. The old way is this:

import { useState } from 'react'
import './App.css'

function App() {
  const [mode, setMode] = useState(true)
  return (
    <>
      <button onClick={() => setMode(!mode)}>
        toggle
      </button>

      {mode && <textarea placeholder="Type something..." rows={4} cols={50} />}
    </>
  )
}

export default App

Enter fullscreen mode Exit fullscreen mode

But with this syntax, when mode is false, the textarea is removed. This means that the state isnt stored. It is crucial to understand the difference.

Ultimate example

I suggest to use this kind of state variable:

 const [mode, setMode] = useState<'visible' | 'hidden'>('visible')
Enter fullscreen mode Exit fullscreen mode

And this function

() => setMode((mode) => (mode === 'visible' ? 'hidden' : 'visible'))
Enter fullscreen mode Exit fullscreen mode

Because the point is to make code more readable as possibile. And I think this is the more readable way to use <Activity /> component.

<Activity mode={mode}>
  <textarea placeholder="Type something..." rows={4} cols={50} />
</Activity>
Enter fullscreen mode Exit fullscreen mode

Here the full example.

import { Activity, useState } from 'react'
import './App.css'

function App() {
  const [mode, setMode] = useState<'visible' | 'hidden'>('visible')
  return (
    <>
      <button onClick={() => setMode((mode) => (mode === 'visible' ? 'hidden' : 'visible'))}>
        toggle
      </button>

      <Activity mode={mode}>
        <textarea placeholder="Type something..." rows={4} cols={50} />
      </Activity>
    </>
  )
}

export default App
Enter fullscreen mode Exit fullscreen mode

My latest books

I am writing a book of notes about React 19.2. I've also published some other books. Italian only at the moment.

JavaScript​: https://amzn.to/479R9DG
TypeScript: https://amzn.to/47w7X87

Top comments (0)