Introduction
React is one of the very popular javascript Library. It is developed by Facebook and is Facebook's first open source projects maintained by its vast community.
It was released with OOP and functional programming paradigm. In it's initial days the dominating paradigm was OOP or say class based components. Maybe due to increase in popularity and ease of functional programming react team developed hooks to make functional way of programming more powerful.
With Hooks, you can extract stateful logic from a component so it can be tested independently and reused. Hooks allow you to reuse stateful logic without changing your component hierarchy. This makes it easy to share Hooks among many components or with the community.
React has around 10-15 built in hooks. Out of which generally 6-7 comes handy during development of any application with reactjs π .
Hooks in react has replaced the lifecycle methods, and so the class components from react (Hooks don't work inside classes). Despite of 10-15 built-in hooks you can make your own custom hooks which can be used in your application at various places honouring the DRY (Do not Repeat Yourself) principle.
Rules to make Custom hooks
There are rules to be followed before/while making the custom hook.
- Only call Hooks at the top level. Don't call Hooks inside loops, conditions, or nested functions.
- We have to use "use" keyword infront of name of hook.
- Only call Hooks from React function components.
- Don't call Hooks from regular JavaScript functions.
find the concept of hook in many other libraries used with react, as in react-router-dom
, redux-toolkit
etc.
What are react hooks?
Hooks are superpower for functional components which are functions that let you βhook intoβ React state and lifecycle features from function components. they let you use React without classes.
With hooks you can store you state data for a particular component, you can perform side effects like API calls, setTimeout, and DOM manipulation (with hooks like useRef
) and many other things which helps you to keep the application work smooth and faster.
How much to use hooks?
If react has given the superpower it doesn't mean that You will use it as much as you want. Remember a thumb rule in react
Lesser the number of re-renders, Faster the app will work.
So before declaring any hook think, if it can work without using the hook. Component hierarchy also matters lot when it comes to where to declare/use a hook in a project.
before starting to learn react or even after having a experience in working with react this page from its docs is worth going through.
Stay happy, Keep your surroundings clean,
Signing off Meet Bhalodiya,
Peace β
Top comments (0)