Articles

Getting started with React Hooks

by Shah Faisal Sr. Digital Marketer Analyst

React Hooks came into production with React v16.8 and it has completely changed the way we were thinking and using React. React Hooks enables us to build components using the functional approach instead of an object-oriented (classes) approach.

So the big question here is – What is React Hooks and why is everyone so excited about them. But before we discuss what React Hooks actually are, it is very important to understand the challenges that we are currently facing with React and how Hooks can help us solve these challenges. 

For a deeper understanding, you can check out the official docs on React Hooks.

Challenges in React

Challenge 1 – Hard to reuse stateful logic between different components

In React, it is very hard to reuse stateful logic between different components. React does not offer a way to attach reusable behavior to a component. 

So if you have worked with React, you do understand things like higher-order components or render props to help solve this issue. 

But even using these patterns require you to refactor your component which is tricky and a little hard to follow. So all React needs is a better way to share stateful logic. This is where React Hooks come into place. 

Challenge 2 – Complex components are harder to understand

Another challenge we were seeing in React is that complex components become hard to understand. Each lifecycle method often contains a mix of unrelated logic. 

So mutually related code that gets split apart with these lifecycle methods whereas completely unrelated code ends up combined in a single method and this makes too easy to introduce bugs and inconsistencies. 

In many cases, it is also not possible to break these components into smaller ones because the stateful logic is all over the place which makes it difficult to test them. 

How React Hooks overcome the challenge in React?

With React Hooks, you can extract stateful logic from a component so that it can be tested independently and reused. Hooks allow you to reuse that stateful logic without any need of changing your component hierarchy and this makes it easy to share React Hooks among different components. 

React Hooks let you split your components into smaller functions based on which pieces are related rather than forcing a split on the lifecycle method. 

So we can separate app concerns based on logic vs. which lifecycle method they belong to.  

Let’s understand the basic syntax difference between React Class and React Hooks by building a simple temperature app.

Read More




Sponsor Ads


About Shah Faisal Innovator   Sr. Digital Marketer Analyst

26 connections, 0 recommendations, 76 honor points.
Joined APSense since, August 20th, 2019, From Mohali, India.

Created on Dec 4th 2019 00:23. Viewed 426 times.

Comments

No comment, be the first to comment.
Please sign in before you comment.