Build your first React Custom Hook

Saba
Geek Culture
Published in
3 min readJun 21, 2021
picture: Morioh

Why we need hooks?

Previously, react was offering props-rendering and higher-order components which make your code reusable. But it was hard to follow and understand. There comes the need of using Hooks in react, which basically allows you to reuse stateful logic without disturbing your component hierarchy. It lets you split your code into smaller functions. There are already some hooks available in the store to use, for example, useEffect, useState, useContext. You can just call them and you are good to go.

But as your code gets complex, you need more control over it which you can do by creating your own custom hook which is aligned with your own project needs. So let’s get started:

What are we creating?

In this tutorial, we will create a custom hook for fetching countries' data from an API. we will be using Countries API.

  1. We will fetch and return all countries if there is no argument.
  2. If a country name is given in the argument, we will return data of that country only.
  3. Example usage of the custom hook:

Pre-requisites:

For this tutorial, we will be assuming that you already have familiarity with the basic concepts of Javascript and React.

Setup for the tutorial:

custom-hook is the name of my react-app, you can name it anything. After the creation of the app, you can change the directory to your app and run “yarn start” to check if your app is running in the browser on localhost.

Next, create useCountry.js in the src folder.

Note: You have to use the “use” keyword with your hook, so that react can recognize that it's a Hook.

Step 1: Write functionality for your Hook.

Note: you can use other hooks in your custom hook.

Step 2: Call and destructure your hook in the main component.

Step 3: Run the code.

Now you can see the response of your First Custom Hook in the browser console.

The code of the hook is also available on Github. In case of further queries, feel free to comment!

In the next episode, you will learn how to render API response to a table with the help of Material-UI.

https://saba-saif.medium.com/designing-in-react-app-with-material-ui-2663be0e43a6

--

--

Saba
Geek Culture

Software Engineer | Full Stack Developer | Traveller | Chef | Artist