DEV Community

Cover image for Create your own custom hook in React
Sadeedpv🥇
Sadeedpv🥇

Posted on • Updated on

Create your own custom hook in React

What is a custom hook in React ?

A custom Hook is just like a JavaScript function whose name starts with ”use” and that may call other Hooks.

Let's create a new custom React hook

So let's create a custom hook to fetch data from an API. We will create an "useLoremipsum" hook to generate lorem ipsum data. Traditionally, this is what we will do:

function App() {
  const [loremipsum, setLoremipsum] = React.useState('');
  console.log(loremipsum)
    React.useEffect(() => {
        const fetchLoremipsum = async () => {
            axios.get(`https://baconipsum.com/api/?type=meat-and-filler&paras=20`)
            .then(res => {
                setLoremipsum(res.data);
            })
        }
        fetchLoremipsum();

    },[])

}
Enter fullscreen mode Exit fullscreen mode

Now let's do the same thing with the "useLoremipsum" hook;
In our App.js file, change the code to:

function App() {
  const baconIpsum = useLoremipsum(2);
  console.log(baconIpsum);
}

Enter fullscreen mode Exit fullscreen mode

Let's create that function "useLoremipsum" that takes in the argument as the length of the lorem-ipsum text in a new file called "useLoremipsum.js".

import React from 'react';
import axios from 'axios';

function useLoremipsum(length) {
    const [loremipsum, setLoremipsum] = React.useState('');

    // Call the function whenever the "length" changes

    React.useEffect(() => {

        const fetchLoremipsum = async () => {

            // Note that we are passing "length" as the argument to "paras" in the URL

            axios.get(`https://baconipsum.com/api/?type=meat-and-filler&paras=${length}`, {
              "Content-Type": 'application/json',
            })
            .then(res => {
                setLoremipsum(res.data);
            })
        }

        fetchLoremipsum();

    },[length])

    // At last, return the data
    return loremipsum;
}

export default useLoremipsum
Enter fullscreen mode Exit fullscreen mode

So, Do I have to name my custom Hooks starting with “use”? No, but it's a good naming convention to follow.
Will the above code work just like the traditional approach? Yes, but building your own Hooks lets you extract component logic into reusable functions.

Conclusion

Custom Hooks offer the flexibility of sharing logic that wasn’t possible in React components before. Next time when you work on a React project, try to spot cases where a custom Hook could hide complex logic behind a simple interface, or help untangle a messy component. Happy coding!

Top comments (0)