Real World Example

Real World: Load orders when the page opens

A "My Orders" page fetches the orders once on load, and again when the user changes the status filter.

function MyOrders() {
  const [status, setStatus] = useState('all');
  const [orders, setOrders] = useState([]);

  useEffect(() => {
    const controller = new AbortController();
    fetch('/api/orders?status=' + status, { signal: controller.signal })
      .then((r) => r.json())
      .then(setOrders)
      .catch(() => {});
    return () => controller.abort();   // user changed the filter quickly
  }, [status]);

  return <OrderList orders={orders} onFilter={setStatus} />;
}