Effects and synchronization

19.3

Use an effect to keep something outside React in sync, such as a browser API, connection, or third-party widget.

On this page

Set up and clean up a listener

Dependencies tell React when the effect needs to run again. Return cleanup for subscriptions you set up. In development, Strict Mode can run an extra setup and cleanup cycle to help reveal bugs.

import { useEffect } from "react";

export function ResizeLogger() {
  useEffect(() => {
    const logWidth = () => console.log(window.innerWidth);
    window.addEventListener("resize", logWidth);
    return () => window.removeEventListener("resize", logWidth);
  }, []);

  return null;
}

Calculate derived values during render

A filtered list can often be calculated from current props and state during render. Keep work caused by a specific click inside the event handler. Reserve effects for synchronization that comes from the component being displayed.

import { useState } from "react";

const products = ["Notebook", "Pencil", "Backpack"];

export default function ProductSearch() {
  const [query, setQuery] = useState("");
  const visibleProducts = products.filter(product =>
    product.toLowerCase().includes(query.toLowerCase())
  );

  return (
    <>
      <label>
        Filter products
        <input value={query} onChange={event => setQuery(event.target.value)} />
      </label>
      <ul>{visibleProducts.map(product => <li key={product}>{product}</li>)}</ul>
    </>
  );
}

Official references