Skip to content

This notebook belongs to

Sadat Jubayer

Senior Software Engineer at Premio

If found, please return to hello@jubayer.dev

Vol. 7Seven years of building

Started
January 2020
Everyday tools
TypeScript, Vue, React, Next.js, NestJS, React Native
Education
B.Sc. CSSE, AIUB, 2020
2 min readReact

Keep tab drafts with React Activity

Hide a React editor with Activity, keep the draft in memory, and let React clean up Effects while the editor is hidden.

You type an unsaved note, hide its editor to make room for a preview, then open the editor again. If the parent renders the editor with showEditor && <Editor />, React removes it when the flag goes false and its draft state starts over next time.

Give the editor a visibility mode

Keep the editor under one Activity boundary and switch the boundary's mode. Render this App in a client app using React 19.2 or later.

import { Activity, useEffect, useState } from 'react'

function Editor() {
  const [note, setNote] = useState('')
  useEffect(() => {
    const ping = () => console.info('editor active')
    const timer = setInterval(ping, 1000)
    return () => clearInterval(timer)
  }, [])

  return (
    <label>
      Draft note
      <textarea value={note} onChange={(e) => setNote(e.target.value)} />
    </label>
  )
}

export function App() {
  const [showEditor, setShowEditor] = useState(true)
  return (
    <>
      <button type="button" onClick={() => setShowEditor((shown) => !shown)}>
        {showEditor ? 'Hide editor' : 'Show editor'}
      </button>
      <Activity mode={showEditor ? 'visible' : 'hidden'}>
        <Editor />
      </Activity>
    </>
  )
}

Type a note, open the console, and wait for “editor active.” Hide the editor and the log pauses. Show it again and the note is still there, with a fresh interval.

Account for the Effects

React hides the editor's DOM with display: none. It keeps the textarea and the state that supplies its value. React runs the Effect cleanup on hide and the setup on reveal. Hidden children can still render in response to props at a lower priority. In this example, cleanup clears the interval, so the hidden editor stops sending messages to the console.

diagram

One draft across two modes

Hiding the editor keeps the textarea and draft state while React clears the interval.

A subscription inside the editor follows that same setup and cleanup pattern. If the hidden editor needs data that must keep updating, put the subscription outside the boundary and pass the current value into the editor.

Keep the same editor identity

If the draft still clears, check the parent JSX. The boundary needs to stay in the tree across toggles. A key that changes on each tab switch gives React a new editor identity, so it starts with a fresh draft.

Use a changing key when you mean to discard the old state, such as when switching to a different document. For two views of the same document, keep the key tied to that document and change the visibility mode.