React Custom Hooks


React

Updated Oct 2nd, 2022

Overview

Much easier than you think. Prevent Code duplication. Encapsulate logic. React components should be simple and only returning some JSX Not every react developer knows how to leverage custom hooks.

Hooks should start with “use” prefix, both the file name and the component name. This lets React do some extra linting and error checking for you.

Allowed to use built-in React hooks inside of your custom hook.

Important form the docs: Two components using the same Hook do not share state. This means a custom hook gets isolated state. Since Hooks are functions, we can pass information between them.

Sources

React Docs here

Web Dev Simplified, Learn in 10 Minutes here to create a “useLocalStorage” hook and at the 7:50 mark, a custom “useUpdateLogger” hook.

JSMastery from 09/2020 to make Random Gif example app here, (Hook content starts at 22 minutes). Simple. The custom hook returns a gif and the “fetchGif” function.