Getting everything ready for you…

Loading courses, problems and your progress. This takes just a moment.

0s

Notes › Web Development

React Hooks — useEffect, useRef, useMemo and Custom Hooks

Hooks let function components have state and side effects. Basics first: React Basics.

Rules of hooks

  1. Call hooks only at the top level — not inside loops, conditions or nested functions.
  2. Call them only from React components or custom hooks. React relies on the call order to match each hook with its stored value.

useEffect — side effects

Use it to sync with things outside React: fetching data, timers, subscriptions, the document title.

useEffect(() => {
  document.title = `${count} clicks`;
}, [count]);            // runs after render when count changes
Dependency array Effect runs
none after every render
[] once, after the first render
[a, b] after the first render and whenever a or b changes

Fetching data (with cleanup)

function Course({ id }) {
  const [course, setCourse] = useState(null);
  const [error, setError] = useState("");
  useEffect(() => {
    let alive = true;                              // ignore results from an old id
    fetch(`/api/courses/${id}`)
      .then((r) => r.json())
      .then((data) => alive && setCourse(data))
      .catch(() => alive && setError("Could not load"));
    return () => { alive = false; };               // cleanup runs before the next effect / on unmount
  }, [id]);
  if (error) return <p>{error}</p>;
  return course ? <h1>{course.title}</h1> : <p>Loading…</p>;
}

Timers and listeners must be cleaned up:

useEffect(() => {
  const t = setInterval(() => setSeconds((s) => s + 1), 1000);
  return () => clearInterval(t);
}, []);

Missing dependencies cause stale values; the react-hooks/exhaustive-deps lint rule catches them.

useRef — a box that survives renders

function Search() {
  const inputRef = useRef(null);
  useEffect(() => inputRef.current.focus(), []);   // 1) access a DOM node
  return <input ref={inputRef} />;
}
const renders = useRef(0);
renders.current++;                                 // 2) mutable value that does NOT cause a re-render

useMemo and useCallback — avoid repeated work

const sorted = useMemo(() => [...items].sort(byScore), [items]);      // remember a computed value
const onSelect = useCallback((id) => setSelected(id), []);            // remember a function

Use them for expensive calculations or when passing functions to components wrapped in React.memo. Don't wrap everything — memoisation has its own cost.

useContext — avoid prop drilling

const ThemeContext = createContext("dark");
function App() {
  const [theme, setTheme] = useState("dark");
  return (
    <ThemeContext.Provider value={{ theme, setTheme }}>
      <Navbar />
    </ThemeContext.Provider>
  );
}
function Navbar() {
  const { theme, setTheme } = useContext(ThemeContext);
  return <button onClick={() => setTheme(theme === "dark" ? "light" : "dark")}>{theme}</button>;
}

Good for the logged-in user, theme, language. Every consumer re-renders when the value changes.

useReducer — complex state

function reducer(state, action) {
  switch (action.type) {
    case "add": return { ...state, items: [...state.items, action.item] };
    case "remove": return { ...state, items: state.items.filter((i) => i.id !== action.id) };
    default: return state;
  }
}
const [state, dispatch] = useReducer(reducer, { items: [] });
dispatch({ type: "add", item });

Custom hooks — reuse logic

A function starting with use that calls other hooks.

function useFetch(url) {
  const [data, setData] = useState(null);
  const [loading, setLoading] = useState(true);
  useEffect(() => {
    let alive = true;
    setLoading(true);
    fetch(url)
      .then((r) => r.json())
      .then((d) => alive && setData(d))
      .finally(() => alive && setLoading(false));
    return () => { alive = false; };
  }, [url]);
  return { data, loading };
}

function useLocalStorage(key, initial) {
  const [value, setValue] = useState(() => JSON.parse(localStorage.getItem(key)) ?? initial);
  useEffect(() => localStorage.setItem(key, JSON.stringify(value)), [key, value]);
  return [value, setValue];
}

Class life cycle → hooks

Class Hooks
componentDidMount useEffect(fn, [])
componentDidUpdate useEffect(fn, [deps])
componentWillUnmount the cleanup function returned by useEffect
this.state / setState useState

Interview one-liners

More Web Development notes