'You Might Not Need an Effect'·续2

updateState();

window.addEventListener('online', updateState); window.addEventListener('offline', updateState); return () => { window.removeEventListener('online', updateState); window.removeEventListener('offline', updateState); }; }, []); return isOnline; }

function ChatIndicator() { const isOnline = useOnlineStatus(); // ... }


Here, the component subscribes to an external data store (in this case, the browser `navigator.onLine` API). Since this API does not exist on the server (so it can't be used for the initial HTML), initially the state is set to `true`. Whenever the value of that data store changes in the browser, the component updates its state.

Although it's common to use Effects for this, React has a purpose-built Hook for subscribing to an external store that is preferred instead. Delete the Effect and replace it with a call to [`useSyncExternalStore`](/reference/react/useSyncExternalStore):

```js {11-16}
function subscribe(callback) {
  window.addEventListener('online', callback);
  window.addEventListener('offline', callback);
  return () => {
    window.removeEventListener('online', callback);
    window.removeEventListener('offline', callback);
  };
}

function useOnlineStatus() {
  // ✅ Good: Subscribing to an external store with a built-in Hook
  return useSyncExternalStore(
    subscribe, // React won't resubscribe for as long as you pass the same function
    () => navigator.onLine, // How to get the value on the client
    () => true // How to get the value on the server
  );
}

function ChatIndicator() {
  const isOnline = useOnlineStatus();
  // ...
}

This approach is less error-prone than manually syncing mutable data to React state with an Effect. Typically, you'll write a custom Hook like useOnlineStatus() above so that you don't need to repeat this code in the individual components. Read more about subscribing to external stores from React components.

Fetching data

Many apps use Effects to kick off data fetching. It is quite common to write a data fetching Effect like this:

```js {5-10} function SearchResults({ query }) { const [results, setResults] = useState([]); const [page, setPage] = useState(1);

useEffect(() => { // 🔴 Avoid: Fetching without cleanup logic fetchResults(query, page).then(json => { setResults(json); }); }, [query, page]);

function handleNextPageClick() { setPage(page + 1); } // ... }


You *don't* need to move this fetch to an event handler.

This might seem like a contradiction with the earlier examples where you needed to put the logic into the event handlers! However, consider that it's not *the typing event* that's the main reason to fetch. Search inputs are often prepopulated from the URL, and the user might navigate Back and Forward without touching the input.

It doesn't matter where `page` and `query` come from. While this component is visible, you want to keep `results` [synchronized](/learn/synchronizing-with-effects) with data from the network for the current `page` and `query`. This is why it's an Effect.

However, the code above has a bug. Imagine you type `"hello"` fast. Then the `query` will change from `"h"`, to `"he"`, `"hel"`, `"hell"`, and `"hello"`. This will kick off separate fetches, but there is no guarantee about which order the responses will arrive in. For example, the `"hell"` response may arrive *after* the `"hello"` response. Since it will call `setResults()` last, you will be displaying the wrong search results. This is called a ["race condition"](https://en.wikipedia.org/wiki/Race_condition): two different requests "raced" against each other and came in a different order than you expected.

**To fix the race condition, you need to [add a cleanup function](/learn/synchronizing-with-effects#fetching-data) to ignore stale responses:**

```js {5,7,9,11-13}
function SearchResults({ query }) {
  const [results, setResults] = useState([]);
  const [page, setPage] = useState(1);
  useEffect(() => {
    let ignore = false;
    fetchResults(query, page).then(json => {
      if (!ignore) {
        setResults(json);
      }
    });
    return () => {
      ignore = true;
    };
  }, [query, page]);

function handleNextPageClick() {
    setPage(page + 1);
  }
  // ...
}

This ensures that when your Effect fetches data, all responses except the last requested one will be ignored.

Handling race conditions is not the only difficulty with implementing data fetching. You might also want to think about caching responses (so that the user can click Back and see the previous screen instantly), how to fetch data on the server (so that the initial server-rendered HTML contains the fetched content instead of a spinner), and how to avoid network waterfalls (so that a child can fetch data without waiting for every parent).

These issues apply to any UI library, not just React. Solving them is not trivial, which is why modern frameworks provide more efficient built-in data fetching mechanisms than fetching data in Effects.

If you don't use a framework (and don't want to build your own) but would like to make data fetching from Effects more ergonomic, consider extracting your fetching logic into a custom Hook like in this example:

``js {4} function SearchResults({ query }) { const [page, setPage] = useState(1); const params = new URLSearchParams({ query, page }); const results = useData(/api/search?${params}`);

function handleNextPageClick() { setPage(page + 1); } // ... }

function useData(url) { const [data, setData] = useState(null); useEffect(() => { let ignore = false; fetch(url) .then(response => response.json()) .then(json => { if (!ignore) { setData(json); } }); return () => { ignore = true; }; }, [url]); return data; }


You'll likely also want to add some logic for error handling and to track whether the content is loading. You can build a Hook like this yourself or use one of the many solutions already available in the React ecosystem. **Although this alone won't be as efficient as using a framework's built-in data fetching mechanism, moving the data fetching logic into a custom Hook will make it easier to adopt an efficient data fetching strategy later.**

In general, whenever you have to resort to writing Effects, keep an eye out for when you can extract a piece of functionality into a custom Hook with a more declarative and purpose-built API like `useData` above. The fewer raw `useEffect` calls you have in your components, the easier you will find to maintain your application.

- If you can calculate something during render, you don't need an Effect.
- To cache expensive calculations, add `useMemo` instead of `useEffect`.
- To reset the state of an entire component tree, pass a different `key` to it.
- To reset a particular bit of state in response to a prop change, set it during rendering.
- Code that runs because a component was *displayed* should be in Effects, the rest should be in events.
- If you need to update the state of several components, it's better to do it during a single event.
- Whenever you try to synchronize state variables in different components, consider lifting state up.
- You can fetch data with Effects, but you need to implement cleanup to avoid race conditions.

#### Transform data without Effects

The `TodoList` below displays a list of todos. When the "Show only active todos" checkbox is ticked, completed todos are not displayed in the list. Regardless of which todos are visible, the footer displays the count of todos that are not yet completed.

Simplify this component by removing all the unnecessary state and Effects.

```js {expectedErrors: {'react-compiler': [12, 16, 20]}}
import { useState, useEffect } from 'react';
import { initialTodos, createTodo } from './todos.js';

export default function TodoList() {
  const [todos, setTodos] = useState(initialTodos);
  const [showActive, setShowActive] = useState(false);
  const [activeTodos, setActiveTodos] = useState([]);
  const [visibleTodos, setVisibleTodos] = useState([]);
  const [footer, setFooter] = useState(null);

useEffect(() => {
    setActiveTodos(todos.filter(todo => !todo.completed));
  }, [todos]);

useEffect(() => {
    setVisibleTodos(showActive ? activeTodos : todos);
  }, [showActive, todos, activeTodos]);

useEffect(() => {
    setFooter(
      <footer>
        {activeTodos.length} todos left
      </footer>
    );
  }, [activeTodos]);

return (
    <>
      &lt;label>
        &lt;input
          type="checkbox"
          checked={showActive}
          onChange={e => setShowActive(e.target.checked)}
        />
        Show only active todos
      &lt;/label>
      &lt;NewTodo onAdd={newTodo => setTodos([...todos, newTodo])} />
      &lt;ul>
        {visibleTodos.map(todo => (
          &lt;li key={todo.id}>
            {todo.completed ? &lt;s>{todo.text}&lt;/s> : todo.text}
          &lt;/li>
        ))}
      &lt;/ul>
      {footer}
    &lt;/>
  );
}

function NewTodo({ onAdd }) {
  const [text, setText] = useState('');

function handleAddClick() {
    setText('');
    onAdd(createTodo(text));
  }

return (
    <>
      &lt;input value={text} onChange={e => setText(e.target.value)} />
      &lt;button onClick={handleAddClick}>
        Add
      &lt;/button>
    &lt;/>
  );
}

```js src/todos.js let nextId = 0;

export function createTodo(text, completed = false) { return { id: nextId++, text, completed }; }

export const initialTodos = [ createTodo('Get apples', true), createTodo('Get oranges', true), createTodo('Get carrots'), ];


```css
label { display: block; }
input { margin-top: 10px; }

If you can calculate something during rendering, you don't need state or an Effect that updates it.

There are only two essential pieces of state in this example: the list of todos and the showActive state variable which represents whether the checkbox is ticked. All of the other state variables are redundant and can be calculated during rendering instead. This includes the footer which you can move directly into the surrounding JSX.

Your result should end up looking like this:

import { useState } from 'react';
import { initialTodos, createTodo } from './todos.js';

export default function TodoList() {
  const [todos, setTodos] = useState(initialTodos);
  const [showActive, setShowActive] = useState(false);
  const activeTodos = todos.filter(todo => !todo.completed);
  const visibleTodos = showActive ? activeTodos : todos;

return (
    <>
      &lt;label>
        &lt;input
          type="checkbox"
          checked={showActive}
          onChange={e => setShowActive(e.target.checked)}
        />
        Show only active todos
      &lt;/label>
      &lt;NewTodo onAdd={newTodo => setTodos([...todos, newTodo])} />
      &lt;ul>
        {visibleTodos.map(todo => (
          &lt;li key={todo.id}>
            {todo.completed ? &lt;s>{todo.text}&lt;/s> : todo.text}
          &lt;/li>
        ))}
      &lt;/ul>
      &lt;footer>
        {activeTodos.length} todos left
      &lt;/footer>
    &lt;/>
  );
}

function NewTodo({ onAdd }) {
  const [text, setText] = useState('');

function handleAddClick() {
    setText('');
    onAdd(createTodo(text));
  }

return (
    <>
      &lt;input value={text} onChange={e => setText(e.target.value)} />
      &lt;button onClick={handleAddClick}>
        Add
      &lt;/button>
    &lt;/>
  );
}

```js src/todos.js let nextId = 0;

export function createTodo(text, completed = false) { return { id: nextId++, text, completed }; }

export const initialTodos = [ createTodo('Get apples', true), createTodo('Get oranges', true), createTodo('Get carrots'), ];


```css
label { display: block; }
input { margin-top: 10px; }

Cache a calculation without Effects

In this example, filtering the todos was extracted into a separate function called getVisibleTodos(). This function contains a console.log() call inside of it which helps you notice when it's being called. Toggle "Show only active todos" and notice that it causes getVisibleTodos() to re-run. This is expected because visible todos change when you toggle which ones to display.

Your task is to remove the Effect that recomputes the visibleTodos list in the TodoList component. However, you need to make sure that getVisibleTodos() does not re-run (and so does not print any logs) when you type into the input.

One solution is to add a useMemo call to cache the visible todos. There is also another, less obvious solution.

```js {expectedErrors: {'react-compiler': [11]}} import { useState, useEffect } from 'react'; import { initialTodos, createTodo, getVisibleTodos } from './todos.js';

export default function TodoList() { const [todos, setTodos] = useState(initialTodos); const [showActive, setShowActive] = useState(false); const [text, setText] = useState(''); const [visibleTodos, setVisibleTodos] = useState([]);

useEffect(() => { setVisibleTodos(getVisibleTodos(todos, showActive)); }, [todos, showActive]);

function handleAddClick() { setText(''); setTodos([...todos, createTodo(text)]); }

return ( <> <label> <input type="checkbox" checked={showActive} onChange={e => setShowActive(e.target.checked)} /> Show only active todos </label> <input value={text} onChange={e => setText(e.target.value)} /> <button onClick={handleAddClick}> Add </button> <ul> {visibleTodos.map(todo => ( <li key={todo.id}> {todo.completed ? <s>{todo.text}</s> : todo.text} </li> ))} </ul> </> ); }


```js src/todos.js
let nextId = 0;
let calls = 0;

export function getVisibleTodos(todos, showActive) {
  console.log(`getVisibleTodos() was called ${++calls} times`);
  const activeTodos = todos.filter(todo => !todo.completed);
  const visibleTodos = showActive ? activeTodos : todos;
  return visibleTodos;
}

export function createTodo(text, completed = false) {
  return {
    id: nextId++,
    text,
    completed
  };
}

export const initialTodos = [
  createTodo('Get apples', true),
  createTodo('Get oranges', true),
  createTodo('Get carrots'),
];
label { display: block; }
input { margin-top: 10px; }

Remove the state variable and the Effect, and instead add a useMemo call to cache the result of calling getVisibleTodos():

```js import { useState, useMemo } from 'react'; import { initialTodos, createTodo, getVisibleTodos } from './todos.js';

export default function TodoList() { const [todos, setTodos] = useState(initialTodos); const [showActive, setShowActive] = useState(false); const [text, setText] = useState(''); const visibleTodos = useMemo( () => getVisibleTodos(todos, showActive), [todos, showActive] );