building react js custom hooks

August 5, 2019

hosein

Articles Tutorials

Creating react custom hooks

React js has come a long way since it’s first release and it’s still being supported and updated by Facebook and it has gained a great developer community.

one of the new features that where introduced in react 16 were hooks, hooks are functions to share logic and functionality between multiple components.

using react custom hooks along with react default hooks can help us not repeat our selves and save us from copy and pasting code from one component to another.

So for simplicity we’re going to create a counter hook, which can be imported and used in any component just like useState, useEffect,etc.

Creating the custom hook

first of all create a js file and name it hooks.js and write the following function in it and export it:

// counter hook
export function useCounter(start, finish) {

}

the function has two inputs, start and finish.

with a hook we can export both state and methods, and in useCounter hook we’ll export count state and increment and decrement methods:

export function useCounter(start, finish) {

    let [count, setCount] = useState(start);

    //reset the counter when the count equals finish
    function increment(){
        if(count < finish){
            setCount(count+1);
        }else{
            setCount(start);
        }
    }
    //
    function decrement(){
        if(count !== 0){
            setCount(count-1);
        }
    }

    return [count, increment, decrement];
}

Usage

after creating the useCounter custom hook we can use it in other components, for example by importing useCounter in App.js we can use it’s state and methods:

import React from 'react';
import {useCounter} from './hooks'

export function App() {
    const [count, increment, decrement] = useCounter(1, 10);

    return <div>
        <h1>{count}</h1>
        <button onClick={decrement}>-</button>
        <button onClick={increment}>+</button>
    </div>;
}

the end result: