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 …


This content originally appeared on DEV Community and was authored by Sadeedpv

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();

    },[])

}

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);
}

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

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!


This content originally appeared on DEV Community and was authored by Sadeedpv


Print Share Comment Cite Upload Translate Updates
APA

Sadeedpv | Sciencx (2022-07-23T09:07:07+00:00) Create your own custom hook in React. Retrieved from https://www.scien.cx/2022/07/23/create-your-own-custom-hook-in-react/

MLA
" » Create your own custom hook in React." Sadeedpv | Sciencx - Saturday July 23, 2022, https://www.scien.cx/2022/07/23/create-your-own-custom-hook-in-react/
HARVARD
Sadeedpv | Sciencx Saturday July 23, 2022 » Create your own custom hook in React., viewed ,<https://www.scien.cx/2022/07/23/create-your-own-custom-hook-in-react/>
VANCOUVER
Sadeedpv | Sciencx - » Create your own custom hook in React. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2022/07/23/create-your-own-custom-hook-in-react/
CHICAGO
" » Create your own custom hook in React." Sadeedpv | Sciencx - Accessed . https://www.scien.cx/2022/07/23/create-your-own-custom-hook-in-react/
IEEE
" » Create your own custom hook in React." Sadeedpv | Sciencx [Online]. Available: https://www.scien.cx/2022/07/23/create-your-own-custom-hook-in-react/. [Accessed: ]
rf:citation
» Create your own custom hook in React | Sadeedpv | Sciencx | https://www.scien.cx/2022/07/23/create-your-own-custom-hook-in-react/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.