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
  • Exploring 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 life-cycle 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 life-cycle 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. Whereas 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.

Figure 9.1 React Hooks let us move related code into a single place and stop mixing unrelated code in life-cycle methods.

9.1 Extracting functionality into custom hooks

9.1.1 Recognizing functionality that could be shared

9.1.2 Defining custom hooks outside your components

9.1.3 Calling custom hooks from custom hooks

9.2 Following the Rules of Hooks

9.2.1 Call hooks only at the top level

9.2.2 Call hooks only from React functions

9.2.3 Using 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