Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between React Custom Hooks and Regular Functions

Tags:

reactjs

What is the difference between a regular JS function, a helper/service function and React Custom Hook?

The similar answers I found didn't give any good examples, so I created this "service" function that I'll be using for example to list some users in an other Function Component :

import axios from "axios";

const useService = () => {
  const fields = [
    { key: "name", _style: { width: "40%" } },
    { key: "email", _style: { width: "40%" } },
  ];

  const getUsers = async () => {
    return await axios.get("http://127.0.0.1:8000/api/users");
  };

  const getBadge = (status) => {
    switch (status) {
      case "Active":
        return "success";
      case "Inactive":
        return "secondary";
      case "Pending":
        return "warning";
      case "Banned":
        return "danger";
      default:
        return "primary";
    }
  };

  return { fields, getUsers, getBadge };
};

export default useService;

I called it useService but I didn't actually use any React hooks here like useEffect, useState etc.. So is this function still a Custom Hook? Is it just a utility/helper function?

What is the difference exactly when we talk about Custom Hooks & Utility/Helper/Service/Normal Functions etc...

like image 730
Dwix Avatar asked Jun 27 '26 11:06

Dwix


1 Answers

So is this function still a Custom Hook? Is it just a utility/helper function?

No it isn't a hook.

Hooks use a stateful closure around the invocation of the function component to store state on behalf of that component instance. That closure is maintained by React.

I needed to read Deep dive: How do React hooks really work before I could wrap my head around hooks.

Recently I also came across:

  • Vanilla Hooks (outside React)
  • Hooks in a Nutshell
like image 194
Peer Reynders Avatar answered Jun 30 '26 03:06

Peer Reynders