YavarTechWorks
Published in

YavarTechWorks

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

Now we will set the state as below

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

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.

3. Call a Custom Hook

Now we will call the Custom Hook from the component where it is needed like below

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 :)

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Nidhin kumar

Nidhin kumar

502 Followers

As a species, we have an inbuilt need to connect with others to communicate and share.