Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

react custom hooks vs normal functions, what is the difference

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*

like image 559
pandith padaya Avatar asked Feb 09 '20 04:02

pandith padaya


People also ask

How is a React hook different from a function?

Hooks are functions that let you “hook into” React state and lifecycle features from function components. Hooks don't work inside classes — they let you use React without classes. (We don't recommend rewriting your existing components overnight but you can start using Hooks in the new ones if you'd like.)

What is the purpose of a custom hook in React?

Custom Hooks are a mechanism to reuse stateful logic (such as setting up a subscription and remembering the current value), but every time you use a custom Hook, all state and effects inside of it are fully isolated.

Should I use custom Hooks React?

Why and When To Use Custom Hooks. The main reason to write a custom hook is for code reusability. For example, instead of writing the same code across multiple components that use the same common stateful logic (say a “setState” or localStorage logic), you can put that code inside a custom hook and reuse it.

Can I use Hooks in normal function?

Don't call Hooks from regular JavaScript functions. By following this rule, you ensure that all stateful logic in a component is clearly visible from its source code.


1 Answers

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.

like image 95
Neha Sharma Avatar answered Sep 20 '22 07:09

Neha Sharma