Create a Custom hook in React

Create a Custom hook in React

If you don’t have time to read but want to know what’s there in this post. Find the quick read 👇

On this Post

In this post, we are going to look at how to create a custom hook in React.

  1. About Hooks

  2. Build a Custom Hook

  3. Call a Custom Hook

1. About Hooks

Hooks are a new addition in React 16.8. They let you use state and other React features without writing a class. Hooks are reusable functions.

Custom Hooks provide you the flexibility to share logic in a way that was previously impossible with React components. Form handling, animation, declarative subscriptions, timers, and possibly many other use cases we haven’t thought of are just a few of the numerous use cases that can be covered by custom Hooks. Additionally, you are able to create Hooks that are just as user-friendly as React’s built-in functionality.

Try not to introduce abstraction too soon. The typical function component in your codebase will probably get lengthier now that it can perform more tasks. Don’t feel pressured to immediately divide it into hooks because this is normal. But we also urge you to begin recognizing situations where a custom Hook could conceal intricate reasoning behind a straightforward interface or help sort out a conundrum.

When you have component logic that needs to be used by multiple components, we can extract that logic to a custom Hook.

Custom Hooks start with “use”. Example: useFetch.

2. Build a Custom Hook

Now we will create a custom hook in our React application. If you have already created the React application create a new folder inside the src directory named hooks and then create a new custom hook named useFetch.

This custom hook will fetch the Gifs from Giphy based on the keyword that we provide.

Now create the basic skeleton for the useFetch hook like below

import { useEffect, useState } from "react";

const useFetch = ({keyword}) => {}

export default useFetch;

Now we will set the state as below

import { useEffect, useState } from "react";

const useFetch = ({keyword}) => {
const [gifUrl, setGifUrl] = useState("");
const fetchGifs = async() => {};

useEffect(() => {
}, [gifUrl]);
return gifUrl;
}

export default useFetch;

Now, we will add the logic to fetch the gifs from Giphy based on the keyword that is provided.

import { useEffect, useState } from "react";

const APIKEY = //add your Giphy API key

const useFetch = ({keyword}) => {
const [gifUrl, setGifUrl] = useState("");

const fetchGifs = async() => {
try {
const response = await fetch(`https://api.giphy.com/v1/gifs/search?api_key=${APIKEY}&q=${keyword.split(" ").join("")}&limit=1`);
const { data } = await response.json();

setGifUrl(data[0]?.images?.downsized_medium.url);
} catch (error) {
setGifUrl("https://metro.co.uk/wp-content/uploads/2015/05/pokemon_crying.gif?quality=90&strip=all&zoom=1&resize=500%2C284");
}
};

useEffect(() => {
if (keyword) fetchGifs();
}, [gifUrl])

return gifUrl;
}

export default useFetch;

What happens in the above snippet is whenever this hook is called the useEffect will be called which will call **fetchGifs()** which will call the Giphy API based on the keyword that we provide.

Once the response is received from Giphy it is parsed down and set as a gifUrl state which will return to the component where we call it.

Congratulations!

In this post, we have seen how to create a custom hook in React.

Will catch up in a new post with more interesting crafts till then Happy Learning :)