React CustomHooks

shubhadip maity
3 min readMay 23, 2020

Hooks are the new features that is being introduced in 16.8, in this we can use STATE without writing in Class syntax.

There are different hooks which are being introduced with different functionality of each:

useStateuseEffectUseContextuseReduceruseCallbackuseMemouseRef

We can implement all the lifecycles methods via these hooks with some subtle changes and we can implement own customHooks. There are few rules when dealing with hooks you can read more on it.

In this article we will see how can we implement your own hooks, will be adding two customHooks i.e useTimer and useDataFetcher. useTimer will have a countdown timer and useDataFetcher will be useful for fetching data on load of a Component.

Lets create a component useTimer.js

import {useEffect, useState} from 'react';function useTimer({timer}) {const [seconds, setSeconds] = useState(timer);
const [isActive, setIsActive] = useState(true);
...
...
...
return {seconds,isActive}};

above code will declare values that can be used for displaying timer values, default value for timer can be set via props isActive will be used to determine whether timer is still running.

Will add in the logic of timer, now to start the timer will have to use UseEffect hook

useEffect(()=>{...let interval = null;if (isActive && (seconds > 0)) {interval = setInterval(() => {
setSeconds(seconds => seconds — 1);
}, 1000);
} else if (seconds === 0) { clearInterval(interval);
setIsActive(false)
}return () => {
return clearInterval(interval);
}
},[isActive, seconds]);...

[isActive , seconds] will act as trigger whenever values of any of these two variables changes useEffect will run.

Also the return callBack will act as replacement for componentWillUnMount and the clearInterval will trigger on unmounting.

And we can use our timer by importing useTimer in our components

...import useTimer from './useTimer';...const { seconds, isActive} = useTimer({timer: 10})
...

Lets create our next customHook useDataFetcher.js. lets set initial Variables and url from which we can have

export default function useFetcher({url}){const [loading, setLoading] = useState(false);
const [error, setError] = useState(null);
const [data, setData] = useState([]);
...
return {
loading,
data,
error
}
}

lets add logic about handling api calls, we will again be using useEffect to work async things

useEffect( ()=>{async function fetchData(){try{ setLoading(true);
const response = await Axios.get(url);
setData(response.data.data)
}catch(e){
setError(e);
}
finally{
setLoading(false);
}
}fetchData();},[url])

loading variable will be used to show loader while dataFetching is going on and data will have result of api call whereas error variable will have errorDetails.

Inside useEffect fetchData will be triggered which is an async function and await is used to wait till data has been received and the setData will set response on data variable which can be available to the parent component.

Now we can include useDataFetcher in any component for e.g.

function About(){const { error, data, loading } = useFetcher({url : "http://dummy.restapiexample.com/api/v1/employees"});if (loading) {return <div>Loading….</div>;}if (!loading && error) {return <div>Something went wrong Try Again Later…</div>;}return (<div>{data.map((elem , index) => {return <div key={index}>{elem.employee_name}</div>;})}</div>)}

In this way we can use hooks to implement our customHooks which can be used across our projects with ease

--

--