react custom hooks vs normal functions, what is the difference
Asked Answered
F

9

111

I'm trying to wrap my head around custom hooks. I understand normal hooks which is just fine, but my question is, when writing a custom hook, what is the difference between that and a normal function? I mean why not call it a normal function instead of calling it something like use*

Fairyfairyland answered 9/2, 2020 at 4:20 Comment(0)
C
55

I believe no one has answered your question exactly. I'm still also understanding the benefits and purpose of having this extra feature called hooks, but I can still share my understanding.

React Hooks are JS functions with the power of react, it means that you can add some logic that you could also add into a normal JS function, but also you will be able to use the native hooks like useState, useEffect, etc, to power up that logic, to add it state, or add it side effects, memoization or more. So I believe hooks are a really good thing to manage the logic of the components in a isolated way.

So, you could have a foo.component.js (UI), a useFoo.js(logic), where useFoo will contain maybe many js functions and one hook to manage that functions and return what it's supposed.

This is an amazing video about react hooks, fully recommended

https://youtu.be/J-g9ZJha8FE

Czernowitz answered 19/11, 2020 at 3:6 Comment(3)
Thanks for sharing this, exactly what I was looking for!Sheepfold
so basically, if your callable has no need for useState or other React hooks, and you're okay with it being called outside of React components, a simple function is appropriate?Eraste
@ecoe, my approach is to create first simple function if react things are not needed, and then in case of need to add some react hooks - move/use a "simple" function inside the hookDudden
F
38

There are some differences and problems that make us use react custom hooks:

  1. First of all, if you use normal functions, with every re-render of the component, this function will be created again and it causes the lack of performance. you may think that it can be fixed by using useCallBack and make react not to create a new function every time it re-renders but it is not the main problem that we are going to solve.
  2. The main problem as the react document has discussed with a brief example of tracking online friends, is avoiding copy-pasting the same logic in different functional components which they need to be stateful too.
  3. If we use normal functions inside a component and use useCallBack to avoid creating a new function every time, we did not solve the problem because in every component we should also copy this logic so this did not solve the problem.
  4. The other solution is to make a function outside the functional component to handle this logic, but there is a big problem: in a normal function outside of the component, we don't have access to states because as we mentioned, this implemented logic is stateful and we have access to states only in react components.

So what is the solution here? yes, Custom React Hooks!

  1. It is a stateful function that uses other react built-in hooks (e.g. useState, useCallback etc.) that can wrap around the stateful logic that you wanted to gather in one place and avoid copy and pasting the same logic in multiple components.
  2. With this approach, you can put your logic outside of the component in another function while you are getting the benefit of stateful functionalities of react.

I hope that this answer may solve your problem and resolve your ambiguity.

Formation answered 26/3, 2021 at 10:32 Comment(3)
In the first part of your answer (the useCallback stuff), it looks like you're confusing a callback function (created within the render phase) and regular functions versus custom hooks (both created outside of React lifecycle). Then the solution at the end doesn't really fit the premise of your answer!?Joris
Point 1 of the "problems" section makes no sense. This is something most people seem to misunderstand. First of all, creating a new function comes with negligible performance cost. Secondly, and most importantly, even if you wrap your function in useCallback, it is still being created with every render! It doesn't magically get ignored, it's still in the code for every render cycle. This is about the identity of this function, you literally get ZERO performance gain from using useCallback, because it is recreating the function no matter what.Theophrastus
The point is that useCallback decides whether to use the newly created function or ignore it, but it is always created in memory, because it's passed as a parameter anyway. The performance gain of useCallback comes from the fact that components using these functions as a prop would only re-render if this function's identity changed. Without useCallback it would re-render on every parent rendering, which is often not necessary.Theophrastus
R
23

From the React docs:

A custom Hook is a JavaScript function whose name starts with ”use” and that may call other Hooks. [...] Its name should always start with "use" so that you can tell at a glance that the rules of Hooks apply to it.

So why define custom Hooks with a special "use" naming prefix?

1.) It tells consumers, that these functions are intended to be used with React and obey to an implicit contract (above mentioned rules).

2.) You can have tooling support which checks and enforces these rules. For example, eslint-plugin-react-hooks utilizes a heuristic that assumes, a function starting with "use" prefix and a capital letter after it is a Hook.

Restrict answered 9/2, 2020 at 5:37 Comment(1)
This is the correct answer. A custom hook is a function whose use is governed by the Rules of Hooks, just like built-in hooks. Since custom hooks typically contain hooks themselves, we have to make sure our custom hooks are only called where it is legal to use hooks generally.Retene
T
21

React Hooks (custom or non-custom) should start with the use prefix. As well as, as per the React Documentation:

1) Hooks should be called from the React code only not from the Regular JS functions. Hence, Hooks' scope is limited to the React code world and has more power to do a lot with React code. Rather than JS, regular functions could be used across application but as react code guidelines keep the code more aligned to react syntax.

2) In the class-based components, the Hooks won't work but regular functions will.

3) In the regular JS functions, you can't access useState, useEffect, useContext etc. but in react custom hooks I can.

Tinct answered 9/2, 2020 at 5:58 Comment(5)
it is NOT mandatory to append name with 'use'. I can still use useState, useEffect, etc given first letter of function is capitalised i.e. react function. see this ex: codesandbox.io/s/react-playground-crjbf?file=/index.jsSwaine
Yes, but best-practice of ReactJS hooks recommends that it should start with the 'use'.Tinct
Yes but why? What benefits does it provide? Why did they add it to the guidelines in the first place?Blackfoot
This "answer" doesn't explain anything.Theophrastus
From the React docs: "Its name should always start with use so that you can tell at a glance that the rules of Hooks apply to it." Also, it's what ESLint uses to distinguish hooks from regular functions.Glycerol
S
7

A custom hook depends on one more other hooks. By design React hooks are meant to be used from a component's render method. You will get a warning if you try to use a hook anywhere else. Custom hooks follow the same convention as built-in hooks because they have to be used in the same fashion. The use prefix is just a convention to identify hook functions which are usually call at the very top of a component render method.

You can name your hook function anything you want but as I mentioned, you will get a warning from React if used outside of a render method.

Skelp answered 9/2, 2020 at 4:37 Comment(4)
maybe I'm missing something, but apart from the documentation and rules about the hooks, what the advantage over just calling this a plain old function (apart from the linting features)?Fairyfairyland
Yes. Your missing the fact that is what is suggested so you can easily identity a hook vs other functions. With that been said you are free to name your functions however you want.Skelp
so lets say I name a hook myCustomFunction instead of naming it useCustomFunction, so apart from the linting and other documented rules, I will not be loosing any functionality as such ?Fairyfairyland
No. You will not lose any functionality. Is just a function. But like i said, since custom hooks are usually composed of other hooks you will get an error if you use your function out of context but this has nothing to do with function name itself.Skelp
G
2

You can call it whatever and it will still work fine. The only advantage is that if you use the “useName” convention, React will check for error whether it correctly follows the rules of hooks. It just makes your task slightly easier.

Gules answered 2/4, 2022 at 10:48 Comment(0)
R
0

As other users have stated custom hooks or hooks, in general, are used where we have to do anything related to react component while other util functions are not tied to react state and won't work is areas where react state logic is in place.

An example of custom hooks be useCustomNavigation which could a list of navigator function like navigateToHome, navigateToCheckout etc. So when you to route to homepage from different parts of code, we just use this hook. Also any logic/feature like analytics, and side effects could be part of navigateToHome function.

An example of Util function could be anything like capitalize which does not has to do anything with react or react component. You cannot create a util function called navigator and add useNavigation.

Rosewood answered 17/8, 2022 at 17:50 Comment(0)
T
0

As I see it, custom hooks have their own specific purpose and have their own characteristics and approach. What I mean is that in certain cases we would want to create a custom hook and not a function.

For example, if you have a need to store some data in the Localstorage you would want to create a custom hook for that and call it "useLocalStorage" and if you want to create a component, let's say a page form, you would want to write a function component.

Difference being that our hook is not a component and shows nothing on our UI. It is simply a logical operation.

The reason I see them as different other than the "logical" example above is that our custom hooks are unique in a way of allowing the usage of other custom hook related hooks. For example, the "useDebugValue" which can only work in a custom hook.

What is weird to me is the way React differentiates a function from a custom hook, which I think is the main cause of the confusion. It "checks" your function name and if it starts with "use" then it's a custom hook. What I think would have been a better option is to change the "const" declaration to a "hook" declaration or give it a unique type.

TL;DR, custom hooks are the logic and will allow the usage of hooks like "useDebugValue" and our functions are mostly UI related.

Thorium answered 1/11, 2022 at 17:11 Comment(0)
F
0

A custom hook is a function that calls other React hooks and so must be called in the context of a React component and according to the Rule of Hooks. The naming convention reminds you of this.

The code in a hook runs exactly as though it was inline in the caller but having it in a hook function makes it reusable and encapsulated with clearly defined inputs and outputs.

Fusibility answered 26/6, 2023 at 17:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.