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.