Table of contents
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:
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.
The bind methods are required for functions to call properly and it is a tedious task to put all the bindings every time.
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.
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.
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.
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.
Stateful logic cant be broken into pieces due to its complexity and increases the code.
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.
Also, the features which are dependent on the lifecycle methods can also be implemented in functional components now.
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.