useEffect·续1

label, button { display: block; margin-bottom: 20px; }
html, body { min-height: 300px; }

Controlling a modal dialog

In this example, the external system is the browser DOM. The ModalDialog component renders a <dialog> element. It uses an Effect to synchronize the isOpen prop to the showModal() and close() method calls.

import { useState } from 'react';
import ModalDialog from './ModalDialog.js';

export default function App() {
  const [show, setShow] = useState(false);
  return (
    <>
      <button onClick={() => setShow(true)}>
        Open dialog
      </button>
      <ModalDialog isOpen={show}>
        Hello there!
        <br />
        <button onClick={() => {
          setShow(false);
        }}>Close</button>
      </ModalDialog>
    </>
  );
}

```js src/ModalDialog.js active import { useEffect, useRef } from 'react';

export default function ModalDialog({ isOpen, children }) { const ref = useRef();

useEffect(() => { if (!isOpen) { return; } const dialog = ref.current; dialog.showModal(); return () => { dialog.close(); }; }, [isOpen]);

return

{children}; }


```css
body {
  min-height: 300px;
}

Tracking element visibility

In this example, the external system is again the browser DOM. The App component displays a long list, then a Box component, and then another long list. Scroll the list down. Notice that when all of the Box component is fully visible in the viewport, the background color changes to black. To implement this, the Box component uses an Effect to manage an IntersectionObserver. This browser API notifies you when the DOM element is visible in the viewport.

import Box from './Box.js';

export default function App() {
  return (
    <>
      <LongSection />
      <Box />
      <LongSection />
      <Box />
      <LongSection />
    </>
  );
}

function LongSection() {
  const items = [];
  for (let i = 0; i < 50; i++) {
    items.push(<li key={i}>Item #{i} (keep scrolling)</li>);
  }
  return <ul>{items}</ul>
}

```js src/Box.js active import { useRef, useEffect } from 'react';

export default function Box() { const ref = useRef(null);

useEffect(() => { const div = ref.current; const observer = new IntersectionObserver(entries => { const entry = entries[0]; if (entry.isIntersecting) { document.body.style.backgroundColor = 'black'; document.body.style.color = 'white'; } else { document.body.style.backgroundColor = 'white'; document.body.style.color = 'black'; } }, { threshold: 1.0 }); observer.observe(div); return () => { observer.disconnect(); } }, []);

return (

); }


---

### Wrapping Effects in custom Hooks

Effects are an ["escape hatch":](/learn/escape-hatches) you use them when you need to "step outside React" and when there is no better built-in solution for your use case. If you find yourself often needing to manually write Effects, it's usually a sign that you need to extract some [custom Hooks](/learn/reusing-logic-with-custom-hooks) for common behaviors your components rely on.

For example, this `useChatRoom` custom Hook "hides" the logic of your Effect behind a more declarative API:

```js {1,11}
function useChatRoom({ serverUrl, roomId }) {
  useEffect(() => {
    const options = {
      serverUrl: serverUrl,
      roomId: roomId
    };
    const connection = createConnection(options);
    connection.connect();
    return () => connection.disconnect();
  }, [roomId, serverUrl]);
}

Then you can use it from any component like this:

```js {4-7} function ChatRoom({ roomId }) { const [serverUrl, setServerUrl] = useState('https://localhost:1234');

useChatRoom({ roomId: roomId, serverUrl: serverUrl }); // ...


There are also many excellent custom Hooks for every purpose available in the React ecosystem.

[Learn more about wrapping Effects in custom Hooks.](/learn/reusing-logic-with-custom-hooks)

#### Custom `useChatRoom` Hook

This example is identical to one of the [earlier examples,](#examples-connecting) but the logic is extracted to a custom Hook.

```js
import { useState } from 'react';
import { useChatRoom } from './useChatRoom.js';

function ChatRoom({ roomId }) {
  const [serverUrl, setServerUrl] = useState('https://localhost:1234');

useChatRoom({
    roomId: roomId,
    serverUrl: serverUrl
  });

return (
    <>
      <label>
        Server URL:{' '}
        <input
          value={serverUrl}
          onChange={e => setServerUrl(e.target.value)}
        />
      </label>
      <h1>Welcome to the {roomId} room!</h1>
    </>
  );
}

export default function App() {
  const [roomId, setRoomId] = useState('general');
  const [show, setShow] = useState(false);
  return (
    <>
      <label>
        Choose the chat room:{' '}
        <select
          value={roomId}
          onChange={e => setRoomId(e.target.value)}
        >
          <option value="general">general</option>
          <option value="travel">travel</option>
          <option value="music">music</option>
        </select>
      </label>
      <button onClick={() => setShow(!show)}>
        {show ? 'Close chat' : 'Open chat'}
      </button>
      {show && <hr />}
      {show && <ChatRoom roomId={roomId} />}
    </>
  );
}

```js src/useChatRoom.js import { useEffect } from 'react'; import { createConnection } from './chat.js';

export function useChatRoom({ serverUrl, roomId }) { useEffect(() => { const connection = createConnection(serverUrl, roomId); connection.connect(); return () => { connection.disconnect(); }; }, [roomId, serverUrl]); }


```js src/chat.js
export function createConnection(serverUrl, roomId) {
  // A real implementation would actually connect to the server
  return {
    connect() {
      console.log('✅ Connecting to "' + roomId + '" room at ' + serverUrl + '...');
    },
    disconnect() {
      console.log('❌ Disconnected from "' + roomId + '" room at ' + serverUrl);
    }
  };
}
input { display: block; margin-bottom: 20px; }
button { margin-left: 10px; }

Custom useWindowListener Hook

This example is identical to one of the earlier examples, but the logic is extracted to a custom Hook.

import { useState } from 'react';
import { useWindowListener } from './useWindowListener.js';

export default function App() {
  const [position, setPosition] = useState({ x: 0, y: 0 });

useWindowListener('pointermove', (e) => {
    setPosition({ x: e.clientX, y: e.clientY });
  });

return (
    <div style={{
      position: 'absolute',
      backgroundColor: 'pink',
      borderRadius: '50%',
      opacity: 0.6,
      transform: `translate(${position.x}px, ${position.y}px)`,
      pointerEvents: 'none',
      left: -20,
      top: -20,
      width: 40,
      height: 40,
    }} />
  );
}

```js src/useWindowListener.js import { useState, useEffect } from 'react';

export function useWindowListener(eventType, listener) { useEffect(() => { window.addEventListener(eventType, listener); return () => { window.removeEventListener(eventType, listener); }; }, [eventType, listener]); }


```css
body {
  min-height: 300px;
}

Custom useIntersectionObserver Hook

This example is identical to one of the earlier examples, but the logic is partially extracted to a custom Hook.

import Box from './Box.js';

export default function App() {
  return (
    <>
      <LongSection />
      <Box />
      <LongSection />
      <Box />
      <LongSection />
    </>
  );
}

function LongSection() {
  const items = [];
  for (let i = 0; i < 50; i++) {
    items.push(<li key={i}>Item #{i} (keep scrolling)</li>);
  }
  return <ul>{items}</ul>
}

```js src/Box.js active import { useRef, useEffect } from 'react'; import { useIntersectionObserver } from './useIntersectionObserver.js';

export default function Box() { const ref = useRef(null); const isIntersecting = useIntersectionObserver(ref);

useEffect(() => { if (isIntersecting) { document.body.style.backgroundColor = 'black'; document.body.style.color = 'white'; } else { document.body.style.backgroundColor = 'white'; document.body.style.color = 'black'; } }, [isIntersecting]);

return (

); }


```js src/useIntersectionObserver.js
import { useState, useEffect } from 'react';

export function useIntersectionObserver(ref) {
  const [isIntersecting, setIsIntersecting] = useState(false);

useEffect(() => {
    const div = ref.current;
    const observer = new IntersectionObserver(entries => {
      const entry = entries[0];
      setIsIntersecting(entry.isIntersecting);
    }, {
       threshold: 1.0
    });
    observer.observe(div);
    return () => {
      observer.disconnect();
    }
  }, [ref]);

return isIntersecting;
}

Controlling a non-React widget

Sometimes, you want to keep an external system synchronized to some prop or state of your component.

For example, if you have a third-party map widget or a video player component written without React, you can use an Effect to call methods on it that make its state match the current state of your React component. This Effect creates an instance of a MapWidget class defined in map-widget.js. When you change the zoomLevel prop of the Map component, the Effect calls the setZoom() on the class instance to keep it synchronized:

```json package.json hidden { "dependencies": { "leaflet": "1.9.1", "react": "latest", "react-dom": "latest", "react-scripts": "latest", "remarkable": "2.0.1" }, "scripts": { "start": "react-scripts start", "build": "react-scripts build", "test": "react-scripts test --env=jsdom", "eject": "react-scripts eject" } }


```js src/App.js
import { useState } from 'react';
import Map from './Map.js';

export default function App() {
  const [zoomLevel, setZoomLevel] = useState(0);
  return (
    <>
      Zoom level: {zoomLevel}x
      <button onClick={() => setZoomLevel(zoomLevel + 1)}>+</button>
      <button onClick={() => setZoomLevel(zoomLevel - 1)}>-</button>
      <hr />
      <Map zoomLevel={zoomLevel} />
    </>
  );
}

```js src/Map.js active import { useRef, useEffect } from 'react'; import { MapWidget } from './map-widget.js';

export default function Map({ zoomLevel }) { const containerRef = useRef(null); const mapRef = useRef(null);

useEffect(() => { if (mapRef.current === null) { mapRef.current = new MapWidget(containerRef.current); }

const map = mapRef.current; map.setZoom(zoomLevel); }, [zoomLevel]);

return (

); }


```js src/map-widget.js
import 'leaflet/dist/leaflet.css';
import * as L from 'leaflet';

export class MapWidget {
  constructor(domNode) {
    this.map = L.map(domNode, {
      zoomControl: false,
      doubleClickZoom: false,
      boxZoom: false,
      keyboard: false,
      scrollWheelZoom: false,
      zoomAnimation: false,
      touchZoom: false,
      zoomSnap: 0.1
    });
    L.tileLayer('https://tile.openstreetmap.org/{z}/{x}/{y}.png', {
      maxZoom: 19,
      attribution: '© OpenStreetMap'
    }).addTo(this.map);
    this.map.setView([0, 0], 0);
  }
  setZoom(level) {
    this.map.setZoom(level);
  }
}
button { margin: 5px; }

In this example, a cleanup function is not needed because the MapWidget class manages only the DOM node that was passed to it. After the Map React component is removed from the tree, both the DOM node and the MapWidget class instance will be automatically garbage-collected by the browser JavaScript engine.


Fetching data with Effects

You can use an Effect to fetch data for your component. Note that if you use a framework, using your framework's data fetching mechanism will be a lot more efficient than writing Effects manually.

If you want to fetch data from an Effect manually, your code might look like this:

import { useState, useEffect } from 'react';
import { fetchBio } from './api.js';

export default function Page() {
  const [person, setPerson] = useState('Alice');
  const [bio, setBio] = useState(null);

useEffect(() => {
    let ignore = false;
    setBio(null);
    fetchBio(person).then(result => {
      if (!ignore) {
        setBio(result);
      }
    });
    return () => {
      ignore = true;
    };
  }, [person]);

// ...

Note the ignore variable which is initialized to false, and is set to true during cleanup. This ensures your code doesn't suffer from "race conditions": network responses may arrive in a different order than you sent them.

```js {expectedErrors: {'react-compiler': [9]}} src/App.js import { useState, useEffect } from 'react'; import { fetchBio } from './api.js';

export default function Page() { const [person, setPerson] = useState('Alice'); const [bio, setBio] = useState(null); useEffect(() => { let ignore = false; setBio(null); fetchBio(person).then(result => { if (!ignore) { setBio(result); } }); return () => { ignore = true; } }, [person]);

return ( <>


{bio ?? 'Loading...'}

</> ); }


```js src/api.js hidden
export async function fetchBio(person) {
  const delay = person === 'Bob' ? 2000 : 200;
  return new Promise(resolve => {
    setTimeout(() => {
      resolve('This is ' + person + '’s bio.');
    }, delay);
  })
}

You can also rewrite using the async / await syntax, but you still need to provide a cleanup function:

```js src/App.js import { useState, useEffect } from 'react'; import { fetchBio } from './api.js';

export default function Page() { const [person, setPerson] = useState('Alice'); const [bio, setBio] = useState(null); useEffect(() => { async function startFetching() { setBio(null); const result = await fetchBio(person); if (!ignore) { setBio(result); } }

let ignore = false; startFetching(); return () => { ignore = true; } }, [person]);

return ( <>


{bio ?? 'Loading...'}

</> ); } ```