React Hooks
Why
Hooks are a new addition in React 16.8. They let you use state and other React features without writing a class.
React Hooks improve the development experience by using composition instead of inheritance, they bring the best part of mixins, sharing logic between components, but with a sophisticated way, Hooks make the need for the patterns prop drilling, render props, and HOCs unnecessary.
React hooks come to solve these nowadays problems:
Wrapper hell (caused by design patterns: HOC, render prop, drilling prop)
Huge components (that hard to test and maintain, hard to co-locate code)
Confusing classes (this keyword, hard to make it reusable)
The rules of hooks
There are two main usage rules the React core team stipulates you need to follow to use hooks which they outline in the hooks proposal documentation.
Don’t call Hooks inside loops, conditions, or nested functions (By following this rule, you ensure that Hooks are called in the same order each time a component renders. That’s what allows React to correctly preserve the state of Hooks between multiple
useState
anduseEffect
calls.)Only Call Hooks from React Functions (It doesn't work without React, Instead, you can call Hooks from React function components or custom hooks)ESLint plugin called eslint-plugin-react-hooks enforces the rules above. This comes in handy in enforcing the rules when working on a project.
ESLint plugin called eslint-plugin-react-hooks
enforces the rules above. This comes in handy in enforcing the rules when working on a project.

Most popular Hooks
Starting with the one you will use the most:
useState: This hook gives us the ability to make functional components has their local state through a very simple API.
useReducer: This hook gave us an easy way to organize our state management, If you are already familiar with Redux you will find this easy to understand and work with.
useEffect: This hook has been made for ‘side effects’, it a combination of
componentDidMount
,componentDidUpdate
, andcomponentWillUnmount
all in one place.useContext: That gave us the ability to pass data, config data in our app, down the components tree without using prop drilling.
useCallback: Gave us a nice performance gain by memoizing the given callback and update it when the given dependencies change.
useMemo: This hook cache some data, saving some compute time on our app and hopefully making it more responsive in the process.
Pros and Cons:
Pros:
functional components (more cleaner in code, less code after transpilation, more performant, better testability)
Reusability (ability to extract and reuse logic between components without introducing extra nesting into the tree)
Cons:
Have to respect its rules, without a linter plugin, it is difficult to know which rule has been broken.
Need a considerable time practicing to use properly (Exp: useEffect).
Be aware of the wrong use
No hooks for error boundaries
Last updated
Was this helpful?