<Activity>·续

return ( <button onClick={onClick}> {children} </button> ); }


```js src/Home.js
export default function Home() {
  return (
    &lt;p>Welcome to my profile!&lt;/p>
  );
}

```js src/Posts.js import { use } from 'react'; import { fetchData } from './data.js';

export default function Posts() { const posts = use(fetchData('/posts'));

return ( <ul className="items"> {posts.map(post => <li className="item" key={post.id}> {post.title} </li> )} </ul> ); }


```js src/data.js hidden
// Note: the way you would do data fetching depends on
// the framework that you use together with Suspense.
// Normally, the caching logic would be inside a framework.

let cache = new Map();

export function fetchData(url) {
  if (!cache.has(url)) {
    cache.set(url, getData(url));
  }
  return cache.get(url);
}

async function getData(url) {
  if (url.startsWith('/posts')) {
    return await getPosts();
  } else {
    throw Error('Not implemented');
  }
}

async function getPosts() {
  // Add a fake delay to make waiting noticeable.
  await new Promise(resolve => {
    setTimeout(resolve, 1000);
  });
  let posts = [];
  for (let i = 0; i < 10; i++) {
    posts.push({
      id: i,
      title: 'Post #' + (i + 1)
    });
  }
  return posts;
}
body { height: 275px; }
button { margin-right: 10px }
b { display: inline-block; margin-right: 10px; }
.pending { color: #777; }
video { width: 300px; margin-top: 10px; aspect-ratio: 16/9; }

Posts was able to prepare itself for a faster render, thanks to the hidden Activity boundary.


Pre-rendering components with hidden Activity boundaries is a powerful way to reduce loading times for parts of the UI that the user is likely to interact with next.

[!NOTE]

Only data read from a source that activates a Suspense boundary, such as a Promise read with use, is fetched during pre-rendering. Activity does not detect data fetched inside an Effect.


Speeding up interactions during page load

React includes an under-the-hood performance optimization called Selective Hydration. It works by hydrating your app's initial HTML in chunks, enabling some components to become interactive even if other components on the page haven't loaded their code or data yet.

Suspense boundaries participate in Selective Hydration, because they naturally divide your component tree into units that are independent from one another:

function Page() {
  return (
    <>
      &lt;MessageComposer />

&lt;Suspense fallback="Loading chats...">
        &lt;Chats />
      &lt;/Suspense>
    &lt;/>
  )
}

Here, MessageComposer can be fully hydrated during the initial render of the page, even before Chats is mounted and starts to fetch its data.

So by breaking up your component tree into discrete units, Suspense allows React to hydrate your app's server-rendered HTML in chunks, enabling parts of your app to become interactive as fast as possible.

But what about pages that don't use Suspense?

Take this tabs example:

function Page() {
  const [activeTab, setActiveTab] = useState('home');

return (
    <>
      &lt;TabButton onClick={() => setActiveTab('home')}>
        Home
      &lt;/TabButton>
      &lt;TabButton onClick={() => setActiveTab('video')}>
        Video
      &lt;/TabButton>

{activeTab === 'home' && (
        &lt;Home />
      )}
      {activeTab === 'video' && (
        &lt;Video />
      )}
    &lt;/>
  )
}

Here, React must hydrate the entire page all at once. If Home or Video are slower to render, they could make the tab buttons feel unresponsive during hydration.

Adding Suspense around the active tab would solve this:

```jsx {13,20} function Page() { const [activeTab, setActiveTab] = useState('home');

return ( <> <TabButton onClick={() => setActiveTab('home')}> Home </TabButton> <TabButton onClick={() => setActiveTab('video')}> Video </TabButton>

<Suspense fallback={<Placeholder />}> {activeTab === 'home' && ( <Home /> )} {activeTab === 'video' && ( <Video /> )} </Suspense> </> ) }


...but it would also change the UI, since the `Placeholder` fallback would be displayed on the initial render.

Instead, we can use Activity. Since Activity boundaries show and hide their children, they already naturally divide the component tree into independent units. And just like Suspense, this feature allows them to participate in Selective Hydration.

Let's update our example to use Activity boundaries around the active tab:

```jsx {13-18}
function Page() {
  const [activeTab, setActiveTab] = useState('home');

return (
    <>
      &lt;TabButton onClick={() => setActiveTab('home')}>
        Home
      &lt;/TabButton>
      &lt;TabButton onClick={() => setActiveTab('video')}>
        Video
      &lt;/TabButton>

&lt;Activity mode={activeTab === "home" ? "visible" : "hidden"}>
        &lt;Home />
      &lt;/Activity>
      &lt;Activity mode={activeTab === "video" ? "visible" : "hidden"}>
        &lt;Video />
      &lt;/Activity>
    &lt;/>
  )
}

Now our initial server-rendered HTML looks the same as it did in the original version, but thanks to Activity, React can hydrate the tab buttons first, before it even mounts Home or Video.


Thus, in addition to hiding and showing content, Activity boundaries help improve your app's performance during hydration by letting React know which parts of your page can become interactive in isolation.

And even if your page doesn't ever hide part of its content, you can still add always-visible Activity boundaries to improve hydration performance:

function Page() {
  return (
    <>
      &lt;Post />

&lt;Activity>
        &lt;Comments />
      &lt;/Activity>
    &lt;/>
  );
}

Troubleshooting

My hidden components have unwanted side effects

An Activity boundary hides its content by setting display: none on its children and cleaning up any of their Effects. So, most well-behaved React components that properly clean up their side effects will already be robust to being hidden by Activity.

But there are some situations where a hidden component behaves differently than an unmounted one. Most notably, since a hidden component's DOM is not destroyed, any side effects from that DOM will persist, even after the component is hidden.

As an example, consider a <video> tag. Typically it doesn't require any cleanup, because even if you're playing a video, unmounting the tag stops the video and audio from playing in the browser. Try playing the video and then pressing Home in this demo:

```js src/App.js active import { useState } from 'react'; import TabButton from './TabButton.js'; import Home from './Home.js'; import Video from './Video.js';

export default function App() { const [activeTab, setActiveTab] = useState('video');

return ( <> <TabButton isActive={activeTab === 'home'} onClick={() => setActiveTab('home')} > Home </TabButton> <TabButton isActive={activeTab === 'video'} onClick={() => setActiveTab('video')} > Video </TabButton>

<hr />

{activeTab === 'home' && <Home />} {activeTab === 'video' && <Video />} </> ); }


```js src/TabButton.js hidden
export default function TabButton({ onClick, children, isActive }) {
  if (isActive) {
    return &lt;b>{children}&lt;/b>
  }

return (
    &lt;button onClick={onClick}>
      {children}
    &lt;/button>
  );
}

```js src/Home.js export default function Home() { return ( <p>Welcome to my profile!</p> ); }


```js src/Video.js
export default function Video() {
  return (
    &lt;video
      // 'Big Buck Bunny' licensed under CC 3.0 by the Blender foundation. Hosted by archive.org
      src="https://archive.org/download/BigBuckBunny_124/Content/big_buck_bunny_720p_surround.mp4"
      controls
      playsInline
    />

);
}
body { height: 275px; }
button { margin-right: 10px }
b { display: inline-block; margin-right: 10px; }
.pending { color: #777; }
video { width: 300px; margin-top: 10px; aspect-ratio: 16/9; }

The video stops playing as expected.

Now, let's say we wanted to preserve the timecode where the user last watched, so that when they tab back to the video, it doesn't start over from the beginning again.

This is a great use case for Activity!

Let's update App to hide the inactive tab with a hidden Activity boundary instead of unmounting it, and see how the demo behaves this time:

```js src/App.js active import { Activity, useState } from 'react'; import TabButton from './TabButton.js'; import Home from './Home.js'; import Video from './Video.js';

export default function App() { const [activeTab, setActiveTab] = useState('video');

return ( <> <TabButton isActive={activeTab === 'home'} onClick={() => setActiveTab('home')} > Home </TabButton> <TabButton isActive={activeTab === 'video'} onClick={() => setActiveTab('video')} > Video </TabButton>

<hr />

<Activity mode={activeTab === 'home' ? 'visible' : 'hidden'}> <Home /> </Activity> <Activity mode={activeTab === 'video' ? 'visible' : 'hidden'}> <Video /> </Activity> </> ); }


```js src/TabButton.js hidden
export default function TabButton({ onClick, children, isActive }) {
  if (isActive) {
    return &lt;b>{children}&lt;/b>
  }

return (
    &lt;button onClick={onClick}>
      {children}
    &lt;/button>
  );
}

```js src/Home.js export default function Home() { return ( <p>Welcome to my profile!</p> ); }


```js src/Video.js
export default function Video() {
  return (
    &lt;video
      controls
      playsInline
      // 'Big Buck Bunny' licensed under CC 3.0 by the Blender foundation. Hosted by archive.org
      src="https://archive.org/download/BigBuckBunny_124/Content/big_buck_bunny_720p_surround.mp4"
    />

);
}
body { height: 275px; }
button { margin-right: 10px }
b { display: inline-block; margin-right: 10px; }
.pending { color: #777; }
video { width: 300px; margin-top: 10px; aspect-ratio: 16/9; }

Whoops! The video and audio continue to play even after it's been hidden, because the tab's <video> element is still in the DOM.

To fix this, we can add an Effect with a cleanup function that pauses the video:

```jsx {2,4-10,14} export default function VideoTab() { const ref = useRef();

useLayoutEffect(() => { const videoRef = ref.current;

return () => { videoRef.pause() } }, []);

return ( <video ref={ref} controls playsInline src="..." />

); }


We call `useLayoutEffect` instead of `useEffect` because conceptually the clean-up code is tied to the component's UI being visually hidden. If we used a regular effect, the code could be delayed by (say) a re-suspending Suspense boundary or a View Transition.

Let's see the new behavior. Try playing the video, switching to the Home tab, then back to the Video tab:

```js src/App.js active
import { Activity, useState } from 'react';
import TabButton from './TabButton.js';
import Home from './Home.js';
import Video from './Video.js';

export default function App() {
  const [activeTab, setActiveTab] = useState('video');

return (
    <>
      &lt;TabButton
        isActive={activeTab === 'home'}
        onClick={() => setActiveTab('home')}
      >
        Home
      &lt;/TabButton>
      &lt;TabButton
        isActive={activeTab === 'video'}
        onClick={() => setActiveTab('video')}
      >
        Video
      &lt;/TabButton>

&lt;hr />

&lt;Activity mode={activeTab === 'home' ? 'visible' : 'hidden'}>
        &lt;Home />
      &lt;/Activity>
      &lt;Activity mode={activeTab === 'video' ? 'visible' : 'hidden'}>
        &lt;Video />
      &lt;/Activity>
    &lt;/>
  );
}

```js src/TabButton.js hidden export default function TabButton({ onClick, children, isActive }) { if (isActive) { return <b>{children}</b> }

return ( <button onClick={onClick}> {children} </button> ); }


```js src/Home.js
export default function Home() {
  return (
    &lt;p>Welcome to my profile!&lt;/p>
  );
}

```js src/Video.js import { useRef, useLayoutEffect } from 'react';

export default function Video() { const ref = useRef();

useLayoutEffect(() => { const videoRef = ref.current

return () => { videoRef.pause() }; }, [])

return ( <video ref={ref} controls playsInline // 'Big Buck Bunny' licensed under CC 3.0 by the Blender foundation. Hosted by archive.org src="https://archive.org/download/BigBuckBunny_124/Content/big_buck_bunny_720p_surround.mp4" />

); }


```css
body { height: 275px; }
button { margin-right: 10px }
b { display: inline-block; margin-right: 10px; }
.pending { color: #777; }
video { width: 300px; margin-top: 10px; aspect-ratio: 16/9; }

It works great! Our cleanup function ensures that the video stops playing if it's ever hidden by an Activity boundary, and even better, because the <video> tag is never destroyed, the timecode is preserved, and the video itself doesn't need to be initialized or downloaded again when the user switches back to keep watching it.

This is a great example of using Activity to preserve ephemeral DOM state for parts of the UI that become hidden, but the user is likely to interact with again soon.


Our example illustrates that for certain tags like <video>, unmounting and hiding have different behavior. If a component renders DOM that has a side effect, and you want to prevent that side effect when an Activity boundary hides it, add an Effect with a return function to clean it up.

The most common cases of this will be from the following tags:

  • <video>
  • <audio>
  • <iframe>

Typically, though, most of your React components should already be robust to being hidden by an Activity boundary. And conceptually, you should think of "hidden" Activities as being unmounted.

To eagerly discover other Effects that don't have proper cleanup, which is important not only for Activity boundaries but for many other behaviors in React, we recommend using <StrictMode>.


My hidden components have Effects that aren't running

When an <Activity> is "hidden", all its children's Effects are cleaned up. Conceptually, the children are unmounted, but React saves their state for later. This is a feature of Activity because it means subscriptions won't be active for hidden parts of the UI, reducing the amount of work needed for hidden content.

If you're relying on an Effect mounting to clean up a component's side effects, refactor the Effect to do the work in the returned cleanup function instead.

To eagerly find problematic Effects, we recommend adding <StrictMode> which will eagerly perform Activity unmounts and mounts to catch any unexpected side-effects.


Sitemap

Overview of all docs pages