Algobook
- The developer's handbook
mode-switch
back-button
Buy Me A Coffee
Tue Mar 21 2023

How to create custom hooks in react

Since React version 16.8, hooks was introduced and completely changed the way how we wrote our components. The traditional class components became obselete and functional components became the way forward.

Built in hooks

React offers a wide range of built in hooks for us to use. Some examples are useState for handling component state variables, useRef for element references and memoization hooks like useMemo and useCallback for performance improvements in our components.

Custom hooks

In this guide, we will show how we can create our own hooks. Custom hooks are a great way of minimizing code duplication and are easy to maintain.

In this example, we will create a very simple configuration hook, which will provide the components with necessary configs.

Let's begin writing our hook, called useConfiguration

// Some example configuration const AppConfig = { nightModeEnabled: !!localStorage.getItem('nightModeEnabled'), locale: 'en-gb', apiUrl: 'https://myapi.com/v1', }; // Our hook export const useConfiguration = (key) => { const config = key ? AppConfig[key] : AppConfig; return { config }; };

In this example, we are given the components the option to get a specific config, or getting the whole object.

And now, lets call it from our component:

// Getting full config const { config } = useConfiguration(); // Getting a specific config const { config: url } = useConfiguration('apiUrl');

Easy peasy, right? Now, this was a very simple example - but we just wanted to show how to create a custom hook. There are many great use cases for extracting logic to one place, and then make the component be as simple as possible.

A great example, shown by W3 schools where they are using a useFetch hook for extracting the logic for fetching data from an API. So instead of writing all the response handling, with errors etc, they show case a great way of just extracting it to a hook, and then invoke it like this is the component:

const [data] = useFetch(url);

As said, there are many ways custom hooks can improve our code and applications, it is just up to us as developers to be creative. I hope you found this simple guide to be helpful. Please let us know if you want us to have more complex examples.

Have a great one!

signatureTue Mar 21 2023
See all our articles