useEffect, it is also possible to create our own custom Hooks. These in turn can use internal Hooks or other custom Hooks, and encapsulate logic in a reusable form. Creating custom Hooks can be really useful if you want to use the same logic in multiple components. Even if the complexity of the component's logic grows, it can be useful to divide it and break it up into custom Hooks with meaningful names in order to keep the current Function component more manageable and readable.
useBackgroundColor()— remember that Hooks always need to start with
use. This Hook expects a valid CSS color and then applies the color as the current background color. It is applied as soon as a component using it is mounted or passes a new value to the custom Hook.
useEffectagain and again, it is worth extracting our first custom Hook:
Tabscomponent which allows us to select content based on three buttons. Depending on which component is currently shown to us, we would like to change the background color of our application. Thus, we can use our
OtherSpecialContent. Two of these components already use our custom Hook
useBackgroundColor()to change the global background color in a
useEffect()once the component has mounted.
useEffect()Hook manually in each component that needs to change its background color. However, this would have led to a lot of code duplication. Instead, we are much better off extracting this logic into its own custom Hook and making it configurable by passing the required color as an argument. This can then be used in as many Function components as we like.
useState(). We're using the state,
accountData, to manage the GitHub user data inside of it. The effect is only ever executed if the username changes. Afterwards, we request the user data for this account from the GitHub API, wait for the response and then write the data of this response using
setAccountData()into state. Finally, we pass the state
accountDataback to the component which has called the Hook in the first place.
RepoInfo. For example, we could implement a search for a particular GitHub Account instead of setting this beforehand. To achieve this, we can use
useState()to create a new state in which we write the account that the user has provided and then pass this state to our Custom Hook.
useEffect()Hook contains the account name in the dependency array, it will be executed once a new user account has been passed in. This means that a new API request will be fired each time we make a change to the search field and will then request the data for the provided account:
access_token=xyz. The token can be generated here: https://github.com/settings/tokens.