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...
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With