Custom React Hooks — A quick and sweet example

The following can be read as a side reference to the official React Doc:

E.Y.
2 min readJun 3, 2020
Photo by Brook Anderson on Unsplash

Custom Hooks

After so many various kinds of hooks, it’s good to know about creating your own hook. In a way, customised hook is nothing else other than a function that 1) has a name starting with “use” and 2) can wrap all other hooks inside it.

For example, a common scenario in React component is to call an API endpoint and use the returned data to set the

  • error state
  • loading state
  • response state

Using customised hook, you can wrap all in one hook call:

const endpoint = ‘https://star-wars-character-search.glitch.me/api';const useFetch = url => {
const [response, setResponse] = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
React.useEffect(() => {
setLoading(true);
setResponse(null);
setError(null);
fetch(url)
.then(res => res.json())
.then(res => {
setLoading(false);
setResponse(res);
})
.catch(error => {
setLoading(false);
setError(error);
});
}, []);
return [response, loading, error];
};
const Application = () => {
const [response, loading, error] = useFetch(endpoint + ‘/characters’);
  • Define your hook structure and give it a name: useFetch`
  • Initialise your other states using the useState hook for error, loading, response
  • Call to api using useEffect, and set your error, loading, response state inside the useEffect
  • ! Important: return your hook values in an array
return [response, loading, error];
  • Assign it inside a component
const [response, loading, error] = useFetch(endpoint + ‘/characters’);

--

--