Custom hooks made easy

By Halil 19 January 2021 755 0
Custom hooks made easy

Hooks??

On February 16, 2019, React 16.8 was released to the public. The release introduced React Hooks.

I don't remember a single project that i started without using react hooks since the release.
Personally i think React Hooks are a complete and better replacement for Classes.

But in this blog i am not going to try and explains why because i am sure there are many other blog posts that gives you a good idea and also thee is he official documentation but still in the end it depends on you if you like classes or functions for your project.

Also i assume that you have basic knowledge of ReactJs and JavaScript.
Here i will try to cover a topic that not many React developers fully understand... Creating custom hooks.

So what are custom hooks ?

Custom hooks are nothing but some functions that you build to do something specific such as a API call. So if you would use a particular API call in many components in your app, then you dont have to build this function again and again in every component. Instead you build this once and use it whereever you need. As community suggests, the function starts with "use" .. useCustoomHook, useFunction, useApiCall etc.

Here is out example very simple that actually you can use in the daily bases of you app if needed: 

First create a new file customHook.jsx


		import { useState, useEffect } from "react";
import axios from "axios";

const useCustomHook = () => {
  const [data, setData] = useState([]);

  useEffect(() => {
    const fetchUsers = async () => {
      await axios
        .get("https://jsonplaceholder.typicode.com/users")
        .then((res) => setData(res.data));
    };

    fetchUsers();
  }, []);
  return data;
};

export default useCustomHook;

		

As you see here, we start out function with "use", and all we do here is using useState and useEffect to make our API call and to hold our data from the response we get. In the end you notice here we return something.. something that we will use when we call this hook from anther component. 
And the way to use this custom hook is like this:


		import useCustomHooks from "./customHook";

const userstoFetch = useCustomHooks();

function App() { 
return (
    <div
      style={{
        display: "flex",
        justifyContent: "center",
        alignItems: "center",
        height: "600px",
      }}
    >
      {userstoFetch.map((elem,index) => (
        <div key={index}>{elem.name}</div>
      ))}
    </div>
  );
}
		

So if you need the data from this API call in other components, you don't need to make it all over again with useEffect and save the data from the response to a other state and repeat this in all components. Here you have it ready set up for you so be used in many other places.

Another very simple custom hook can be that we make all the logic and state saved in this particular hook, and we return the value we need and the function that changes this value. 
In a new file named CustomHooksTwo.jsx:


		import { useState } from "react";

const CustomHooksTwo = () => {
  const [count, setCount] = useState(0);
  const updateCount = () => {
    setCount((prev) => prev + 1);
  };
  return { count, updateCount };
};

export default CustomHooksTwo;

		

and in out main component, where we need to use this, we just import it and use it like this..


		import React from "react";
import useCustomHooksTow from "./CustomHooks2";

function App() {
const incrementNr = useCustomHooksTow();

return (
    <div
      style={{
        display: "flex",
        justifyContent: "center",
        alignItems: "center",
        height: "600px",
      }}
    >
      <div>count: {incrementNr.count}</div>
      <button onClick={incrementNr.updateCount}>Increment</button>
    </div>
  );
}
		

On the click of that button we just increment by 1, a function returned from our custom hook above. Very easy, isn't it.
Of course we can do way more complicated things, like to pass arguments from our main data source when we call the hook to the custom hook itself and work on that data. Like any other function, same logic applies here.
Custom hooks makes the code cleaner and easier to work with in big code bases. I would recommend to keep those hooks in a custom folder.