Why Hooks are introduced in React and its use cases

Table of contents

No heading

No headings in the article.

React has introduced the 'hooks' feature in version 16.8 onwards and it's one of the prime features which can replace the class components. First, we have to understand the reasons why they had to introduce it and what problems it solves.

These problems are as follows:

  1. The 'this' keyword works differently in javascript and class-based architecture of Object orientation. This was causing the issue with lexical scoping in class components.

  2. The bind methods are required for functions to call properly and it is a tedious task to put all the bindings every time.

  3. Classes don't minify well and cause trouble while hot reloading due to changes in props and states. Hot reloading means updating the part of the DOM without reloading it completely.

  4. Sharing of the stateful logic within components is not so convenient in class components. HOCs and Render Props create complexity and wrapping of components which again gets complicated for large-scale projects.

  5. While implementing of the features such as data fetching, we have to use two lifecycle methods i.e. componentDidMount and componentDidUpdate. Hooks can implement the same within a single function, the 'useReducer' hook.

  6. The same goes with a subscription to the events, where compnentDidMount and compnentWillUnmount have to be used and can be replaced with a single function.

  7. Stateful logic cant be broken into pieces due to its complexity and increases the code.

  8. There was no provision for the declaration of the states inside the functional components before hooks, so it gives the flexibility to declare states in functional components as well.

  9. Also, the features which are dependent on the lifecycle methods can also be implemented in functional components now.

  10. React has not deprecated the class components due to the introduction of the hooks, so we can use both things together.

So, react has made hooks and newer versions 100% backward compatible which will not discard our knowledge of class-based components. Hence, it's important to understand the usage of hooks and what wonders they can produce in your application. Thank you.

Did you find this article valuable?

Support Ajinkya Chanshetty by becoming a sponsor. Any amount is appreciated!