How to create your own custom hooks stateful functions in React JS

The Hook is an additional feature provided in React Version 16.8 onwards. A hook lets you create a functional state and reuse the logic in different functional components.

Rules of Creating a Hook

  1. The function name must always start with keyword use as a prefix. Example: useAuth, useCart etc.
  2. The Hook function is just like a normal function except it does not return any HTML, but instead, returns state functions and attributes.
  3. To use the hook import it and use it within any other functional component.
    Example

    function MyProfile(){
        const auth = useAuth()
    }
    

    The function useAuth() is a hook.

Caution

Hooks only work with functional components and they don’t work with the class components. To learn more read Introduction of Hooks.

In this post, I’ll show how to create a custom hook using posts as an example. Before that open your react project and configure absolute imports.
In jsconfig.json

{
    "compilerOptions": {
        "baseUrl": "src"
    },
    "include": ["src"]
}

Creating Custom Hook

In src\lib\hooks.js

import React, { useEffect, useState } from 'react'

export default function usePosts(  ){
    const [ posts, setPosts ] = useState( [] )
    const [ isLoading, setIsLoading ] = useState( false )
    const [ count, setCount ] = useState( 0 )

    useEffect( ( ) => {
        setCount(posts.length)
    }, [ posts ] )

    const fetchPosts = async( ) => {
        setIsLoading(true)

        let url = `https://jsonplaceholder.typicode.com/posts`
        let res = await fetch( url )
        res = await res.json()

        if( res.length ){
            setPosts([...res])
        }

        setIsLoading(false)
    }

    return {
        posts,
        fetchPosts,
        count,
        isLoading,
        setIsLoading,
    }
}

The hook usePosts will fetch all the posts from API and set to setPosts() a state management function.
Here we specify three states they are:

  • In [ posts, setPosts ] posts will be a store that is retrieved by fetchPosts() function.
  • [ isLoading, setIsLoading ] state sets whether the posts are loading or not
  • [ count, setCount ] returns the count of posts.

The post data are retrieved using JSON Placeholder.
The name of the hook function must always start with the use keyphrase.

You can also check out other related posts on How to Import Components using Absolute Imports in React JS

Modifying App Component

Now import the hook function usePosts and use it in App the functional component.
In src\App.js

import usePosts from 'lib/hooks';
import React from 'react';

function App() {

    const posts = usePosts()

    return (
        <>

            <h1>Posts | <button onClick={ posts.fetchPosts } type="button" >Load Posts </button> </h1>

            { posts.count > 0 ? <div>Total Posts : {posts.count} </div> : null }

            <div>
            {
                ( !posts.isLoading )
                ? ( posts.posts.length )
                    ? posts.posts.map( (item, index) => {
                        return (
                            <div key={index} style={ { border : '1px solid #eee', padding : '10px 5px' } } >
                            <p>Title: { item.title }</p>
                            <p>{ item.body }</p>
                            </div>
                        )
                        } )
                    : null

                : (
                    <div>Please wait...</div>
                )
                
            }
            </div>

        </>
    )

}

export default App;    

The posts are loaded when the button is clicked and displayed as a list. The count of the posts is also displayed at the top.

Render App Component

In src\index.js

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';

ReactDOM.render(
    <React.StrictMode>
        <App />
    </React.StrictMode>,
  document.getElementById('root')
);

In the end, import the App component and render it.

Output

The final output of how to create your own custom hooks in react js

Watch Video

Sandbox

View complete code on my Github Repository.

Summary
Review Date
Reviewed Item
How to create your own custom hooks stateful functions in React JS
Author Rating
51star1star1star1star1star
Software Name
React JS
Software Name
Windows Os, Mac Os, Ubuntu Os
Software Category
Web Development