A Custom Hook is just a JavaScript Function, which name start with "use"

A Custom Hook can use other React Hooks inside the Hook.

Why to Build Custom Hooks

To Segerate the Logic from the Components. Components are for Presentation only don't put the other stuff inside it , Just Hook the OtherStuff. 😇

Use of Hooks make Component Code Cleaner

In this example we are going to create a LocalStorage hook , which is responsible for Set and Get value in Local Storage ,and we call this Hook from the Component. Let's see the Example

Hook Example

Build a storage-hook.js file

export const useLocalStorage = ()=>{
    const setLocalStorage =(key, value)=>{
        localStorage.setItem(key, JSON.stringify(value));
    }
    const getLocalStorage = (key)=>{
        return JSON.parse(localStorage.getItem(key));
    } 
    return [setLocalStorage, getLocalStorage];    
}

In this Example , a Hook contains the operations and return all the operations (functions) in an array, so we call the hook and get the operations, these operations (functions) contains the logic stuff inside the hook , we simply call these  operations from the component and use it.

From the Component File call the Hook.

const [setLocalStorage,getLocalStorage] = useLocalStorage(); // Calling the Hook

Calling the Operations from the Component

setLocalStorage('user', userObject);
console.log('get local storage data is ', getLocalStorage('user'))

That's All Folks, to Build Custom Hooks....