liveBook · Manning

Callback

As explained in React in Depth

A callback function is a function supplied to another function or API to be invoked as part of that operation.

A callback is a function supplied to another function or API so that the receiving operation can invoke it later or at a defined interaction point. In React, callbacks commonly cross component boundaries as props, connect event handlers to state updates, and expose behavior from custom hooks. section 10.2.2 section 2.3.3

Use callbacks deliberately in component and hook designs:

  • Pass an onDelete callback to a list component, then invoke it with the selected item from the button handler. section 10.2.2
  • Return action callbacks such as addTask and toggleTaskCompletion from a custom hook so a component can coordinate state without owning its implementation. section 2.3.3
  • Memoize a callback when stable identity supports memoized child components and avoids unnecessary rendering of unchanged list items. section 6.1.6
  • Type nested callbacks explicitly when inference no longer has nearby prop context, especially for callbacks receiving an index and returning an event handler. section 6.1.6

Testing an event callback

A todo list receives onDelete, invokes it when a button is clicked, and can be tested with a Vitest mock: render Items with mockDelete, click the button named Delete 'Item B', and assert that mockDelete was called with 'Item B'. section 10.2.2

Listing 6.6 The playlist with a memoized callback
import { useReorderable } from "./useReorderable";
import "./playlist.css";
import { ActionType, Song } from "./types";
import { PlaylistItem } from "./PlaylistItem";
import { MouseEvent, useCallback } from "react";
interface PlaylistProps {
  songs: Song[];
}
export function Playlist({ songs }: PlaylistProps) {
  const [list, dispatch] = useReorderable(songs);
  const handleMove = useCallback(
    (index: number) =>     #1
     (evt: MouseEvent<HTMLButtonElement>) => {   #1
      const type = evt.currentTarget.name as ActionType;
      dispatch({ type, index });
    },
    [dispatch]
  );
  return (
    <ol>
      {list.map((song, index) => (
        <PlaylistItem
          key={song.id}
          song={song}
          index={index}
          move={handleMove}
        />
      ))}
    </ol>
  );
}

Inspect the memoized playlist callback, including its typed nested event handler, dependency array, and reuse by each PlaylistItem. section 6.1.6

How React in Depth covers it

How deep it goes
Explains invocation, prop passing, custom-hook exports, TypeScript signatures, memoization, and callback testing.
Examples
Uses task managers, todo deletion, and reorderable playlists to demonstrate callback composition, testing, typing, and memoization.
What it assumes
Assumes React fundamentals and introduces callback-specific TypeScript typing, hook composition, memoization, and mock-based testing.
What you can do after
Build it from scratch by passing, typing, memoizing, composing, and testing callbacks in React components and hooks.
How it connects
Ties callbacks to React props, event handlers, custom hooks, useCallback, memoization, useReducer, TypeScript, and unit testing.

Also explained in

Compare how 19 books explain callback →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of React in Depth. The section links point to the parts of the book it draws on.