A custom hook is a reusable function that extracts React Hook logic from a function component. It keeps related state and side effects together, shortens components, and lets multiple components share behavior. Each call can maintain its own state, while the hook returns only the values or functions its caller needs. section 1.3.2 section 9.1
Build and use a custom hook by following these practices:
- Identify related functionality, such as fetching data, subscribing to a service, updating a document title, or tracking window dimensions. section 9.1 section 9.3.1
- Define the function outside the component, in the same file or an imported utility file, and begin its name with “use.” section 9.1.2
- Call built-in hooks or other custom hooks inside it; custom hooks may compose useState, useEffect, useContext, and additional custom hooks. section 9.1.3
- Accept parameters for behavior that varies, and return primitives, functions, objects, arrays, or nothing according to the component’s needs. section 9.0 section 9.6
- Call hooks only from React function components or custom hooks; never place hook calls in conditionals, loops, nested functions, or regular JavaScript functions. section 9.2.2 section 9.6
Extracting a document-title effect
A SayHello component can delegate title updates to useDocumentTitle: the component chooses a greeting and calls useDocumentTitle(greetings[index]), while the hook runs useEffect and updates document.title whenever title changes. A further useRandomTitle hook can own the index, call useDocumentTitle, and return a function that selects the next greeting. The component then renders only a button wired to that returned function. section 9.1.1 section 9.1.3
Reusable application hooks
useWindowSize can manage resize listeners and return width and height. useUser can hide Context API details, return a user and updater function, and throw an error when its provider is missing. useFetch can accept a URL and return data, status, and error for loading, success, and failure UI. section 9.3.1 section 9.4 section 9.5
Figure 1.12 You can extract code into custom hooks for reuse and sharing. The Quiz component calls both the useUsers and useFetch hooks. The Chat component calls the useUsers hook.
Shows reuse across components: Quiz calls useUsers and useFetch, while Chat calls useUsers. section 1.3.2



