React Custom Hooks

React Custom Hooks

ยท

4 min read

React Hooks are v16.8 specification which allows certain backward compactible functionalities without any use of class based ordering.

Let's see how to build a customized hook.

TL;DR

Hooks ain't constrained to those built by react core team. We can build our own hooks and specify the behind the hood functionalities, arguments, scopes and whatsoever.

Hooks are mere functions but the fact that they go easily with the react lifecycle, and can be instantiated whenever a functional component is rendering, makes custom hooks special.

Custom Hook

If we could recall the react hooks streak post in my blogs, those patterns and best practices are to be followed while creating a custom one.

  • Naming conventions to begin with 'use' keyword
  • Include the functionalities in a separate file
  • Get the apt arguments
  • Return simple data structures

Steps to follow for building a custom hook is as follows:

  1. Create a separate files with the name of the hooks and define the functionalities to be undergone with specified arguments and return a simple data structure.

  2. Import the file in the component where the functionality is required and the make sure the input are avail.

  3. Destructure the required data by calling the hook and do whatever with the data.

Custom hook in action

Here we build a useFetch() hook that takes in the url and returns the array of data as products, and a boolean loading.

useFetch.js

import { useState, useEffect } from 'react';

export const useFetch = (url) => {
  const [loading, setLoading] = useState(true)
  const [products, setProducts] = useState([])

  const getProducts = async () => {
    const response = await fetch(url)
    const products = await response.json()
    setProducts(products)
    setLoading(false)
  }

  useEffect(() => {
    getProducts()
  }, [url]);

  return { loading, products };
};

The useFetch() hook is consumed in the below component to display the fetched data.

Example.js

import React, { useState, useEffect } from 'react'
import { useFetch } from './useFetch'

const url = 'https://course-api.com/javascript-store-products'

const Example = () => {
  const { loading, products } = useFetch(url);
  return (
    <div>
      <h2>{loading ? 'loading...' : 'data'}</h2>
    </div>
  )
}

export default Example

Major Takeaway

We are all good to build react hooks with our own functionalities and needs just follow on with some best practices

Let's connect ๐Ÿ”—

Catch me here ๐Ÿ‘‡


Hope you all liked the post, share your impressions and queries below ๐Ÿ™Œ

ย