chapter nine

9 Creating your own hooks

 

This chapter covers

  • extracting functionality into custom hooks
  • following The Rules of Hooks
  • consuming a context value with a custom hook
  • encapsulating data fetching with a custom hook
  • further examples of custom hooks

React hooks promise to simplify component code and to promote encapsulation, reusability and maintainability. They let function components work closely with React to manage state and hook into lifecycle events for mounting, rendering and unmounting. Function components with hooks collocate related code and remove the need to mix unrelated code within and across the separate lifecycle methods of class-based components. Figure 9.1 contrasts the location of code in class-based and function-based versions of a Quiz component that loads question data and subscribes to a user service. Where the class component spreads the functionality across its methods, the Quiz function component manages local state with calls to useState or useReducer and wraps up the loading of question data and the subscription to a user service within separate calls to useEffect.

9.1       Extracting functionality into custom hooks

9.1.1   Recognizing functionality that could be shared

9.1.2   Defining custom hooks outside of your components

9.1.3   Calling custom hooks from custom hooks

9.2       Following The Rules of Hooks

9.2.1   Only call hooks at the top level

9.2.2   Only call hooks from React functions

9.2.3   There’s an ESLint plugin for the rules of hooks

9.3       Extracting further examples of custom hooks

9.3.1   Accessing window dimensions with a useWindowSize hook

9.3.2   Getting and setting values with a useLocalStorage hook

9.4       Consuming a context value with a custom hook

9.5       Encapsulating data fetching with a custom hook

9.5.1   Creating the useFetch hook

9.5.2   Using the data, status and error values the useFetch hook returns

9.5.3   Creating a more specialized data-fetching hook: useBookings

9.6       Summary