React Native theorytheory 0/50 · 0%
Hooks · easy

6. useEffect

Running side effects and cleaning them up.

`useEffect` runs after render for side effects: subscriptions, timers, fetches. Returning a function from the effect cleans it up before the next run or on unmount.

import { useEffect, useState } from "react";

function usePrice(symbol: string) {
  const [price, setPrice] = useState<number | null>(null);
  useEffect(() => {
    let cancelled = false;
    fetchPrice(symbol).then((p) => { if (!cancelled) setPrice(p); });
    return () => { cancelled = true; };
  }, [symbol]);
  return price;
}

The dependency array controls when the effect re-runs: omitting it runs on every render, `[]` runs once on mount, and `[symbol]` re-runs whenever `symbol` changes.

Check your understanding

  1. 1. When does an effect with dependency array `[]` run?

  2. 2. What does the function returned from useEffect do?

  3. 3. Why guard an async effect with a `cancelled` flag?