Implement Your Own Hooks
Learn how to build your own Hooks and extract component logic into reusable functions.
Apart from the internal Hooks such as useState
or 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.
Your first custom Hook
Let’s start with a relatively simple example and assume that we want to create a custom Hook with which we can invoke side effects and change the background color of a component whenever it is mounted. A typical name for such a custom Hook would be
useBackgroundColor()
.
Note: 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’s applied as soon as a component using it is mounted or passes a new value to the custom Hook.
Custom Hooks
We might want to use this logic in other components but don’t want to continuously repeat ourselves and implement the same functionality with useEffect
. it’s worth extracting our first custom Hook:
// useBackgroundColor.js
import { useEffect } from 'react';
const useBackgroundColor = (color) => {
useEffect(() => {
document.body.style.backgroundColor = color;
return () => {
document.body.style.backgroundColor = '';
};
}, [color]);
};
export default useBackgroundColor;
Using a custom Hooks inside function components
To use our custom Hook component defined above, we create a Tabs
component that 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. So, let’s use our useBackgroundColor()
Hook:
Get hands-on with 1400+ tech skills courses.