What are Hooks in Reactjs?

Konfinity
September 12,2020 - 15 min read
What are hooks in reactjs

React 16.8 came with a gift for all React developers. Reactjs hooks, launched at the React conference in October of 2018, is a feature that lets you use all other features without the usage of class.

Implementing Reactjs hooks is not difficult but what is important and necessary is understanding the importance and need of Hook. Here, we would start by tracing the need of Reactjs hooks.

Primarily, Hook eliminates the use of class to access features of React. If you read carefully, it eliminates the use of class but not classes itself. Hooks only provide a direct API to the React components you already know.

If you still want to use classes you can continue with them. Take your time to get used to this brand-new concept of Hooks. You can continue with classes and switch to Hooks only when you are comfortable.

But the question remains the same, why use Reactjs Hooks, what problems it solves and what new it brings to the table? Let’s dig deep and understand about the preliminary problems that Reactjs hooks solve and talk about amazing new features that it has to offer.

Problems that Reactjs Hooks Solve

The elimination of classes in using React components have a lot of advantages because developers often find it cumbersome to use classes. It’s relatively easy to understand state, props, uni-directional flow and other features but it is difficult to use and understand classes.

Another complication is regarding the this keyword. If you want to use classes, understanding of this keyword is necessary. But the problem is that the use of this keyword is slightly different in Javascript than in other programming languages. Developers felt that this was like extra burden on their shoulders. Reactjs hooks takes of this load as it eliminates the use of classes and hence the need of this keyword.

Classes in React do not minify very well and make the process of injecting new versions of edited file at runtime very unreliable. Reactjs hook solves or rather eliminates the root cause of this problem i.e the classes.

In React, there was no other defined way to reuse stateful component logic between components. If you attempt, you end up restricting components and making the code look awkward and difficult. There was a pressing need to share stateful logic in a more efficient way. Reactjs hooks come to the rescue as they allow us to reuse stateful logic without tampering with the component hierarchy.

Complex components become hard to understand. Creating complex scenarios such as data. The related code is not organized at one place but scattered at different lifecycle methods. Developers have often dreamt about all related code at one place and not scattered at different places. Hook lets you separate components into smaller functions based the relation between them rather than forcefully splitting based on lifecycle methods.

Before we move on to the actual implementation Reactjs hooks and its various types, we need to have a look at some basic rules. These rules make sure that we do not deviate or digress while using Reactjs hooks.

Rules of Reactjs

Let us now look at some basic rules that we need to follow when working any Reactjs hooks.

The first rule we are going to talk about is the Top-Level rule. This rule simply states that Reactjs hooks can only be called at the top level and not inside loops, nested functions or conditions. The logic behind this rule is that the order of calling remains the same when a component render. This ensures the preservation of state of hooks between different calls.

The second major rule is that Reactjs hooks can only be called within React functions or they can be called from custom Hooks but not ordinary Javascript functions. This rule makes sure that all stateful logic is clear and evident.

If these rules and terminologies don’t make sense, there is no need to panic. Read on the article, get familiarized with Reactjs hooks, make yourself comfortable and then you can always come back to the technical part for reference.

Understanding Reactjs Hooks

Now that we have a solid understanding of the ‘Why’, let’s understand the ‘How’. In simpler terms, we know why the need for the introduction of Reactjs hooks arose and now we have to proceed with how can we implement Hooks in our own React code.

Here we are going to talk about three basic Reactjs hooks, namely useState, useEffect and useContext.

useState

The first hook we are going to talk about is stateHook. This hook allows users to add React state to function components without the use of class. Earlier, states could only be added in function components using classes.

There is a small code that clearly explains the use of stateHook in React.

  1. Import React, {useState} from ‘react’;
  2. Function Example() {
  3. Const [count, setCount] = useState(0);
  4. Return (
  5. <div>
  6. <p>You clicked {count} times</p>
  7. <button onClick={()=> setCount(count + 1)}>
  8. Click me
  9. </button>
  10. </div>
  11. );
  12. }

Just for an overview, the output of this code gives “You clicked {count} times.” The variable count holds the value, the number of times the user clicks. Now that we know the output, let’s understand how we got here using the concept of Hooks in Reactjs.

In the first step, we import useState Hook from React. Further we create a component by the name ‘Example.’ Usestate hook is basically a function, so it accepts an argument just like every function does. In this example, the useState function accepts the initial value of state property as argument and returns the final value of state property.

Inside this variable we declare a new state variable setCount and initialized to 0 or any default value, using square brackets and the useState hook. The variable count stores the current state value, that is, the number of times user has clicked and setCount accepts the argument and set count value to that argument.

When you click on button, setCount is called and value of count is increase. This method updates and stores the value of current state property. setCount method causes the component to re render and the count contains the incremented value. The incremented value is shown with the static text mentioned in the code.

Now that you have a hang of the technical part, you know that setCount (a Reactjs hook) works in an actual code. Let’s move on to other Reactjs hooks.

useEffect

Earlier, we had implemented stateHook and understood its implementation extensively. There is another Reactjs hook which is called the useEffect hook. Developers working with class component often deal with side effects. Render methods are too early to perform and hence lifecycle methods are used. The procedure used solves the purpose well but developers have always wished for an easier and more efficient process. The useEffect came to rescue because it lets you use side effects in functional components. useEffect is a replacement to lifecycle methods componentDidMount, componentDidupdate and componentWillUnmount because it is capable of doing what all these methods were used for in class components.

One important point to note is that the useeffect hook is called after every render. In some cases, calling useEffects is called after every render function might create performance problems. For this reason, we need a way to conditionally run an effect from a functional component. Summarizing, the useEffect hook is used for causing side effects in functional components and mimics the function of certain lifecycle methods.

It would be great if you implement useEffect hook yourself powered by the knowledge of Reactjs hooks that you have garnered till now coupled with extra tips you would be compel to take from the world wide web.

useContext

Another Reactjs hook goes by the name of useContext. Primarily this Reactjs hook allows passing data from parent component to child component without using Redux. useContext deals with the problem of ‘Prop Drilling’.

Imagine that in a deeply nested and complex hierarchy of React components, the parent component needs to pass data not to its immediate child but to a grandchild or great grandchild. This might cause scalable issues because the process of updating prop at each child component can be redundant, lengthy and error prone.

useContext takes you out of this mess, because instead of passing down props through each component you can tunnel through these components with the help of useContext in React. It is a good alternative to Redux when you want to pass data around. useContext provides all the same functionalities that a standard Context API does. One can imagine useContext a package of easy to use methods that you can use inside a functional component.

useContext sounds great but in application it is even more amazing! We would love if you implement this Reactjs hook yourself and share your experience with us in the comments below.

We have discussed the three basic Reactjs hooks - useState, useEffect and useContext. Apart from these, other Reactjs hooks are useReducer, useRef, useLayoutEffect, useCallback, useMemo, useImperativeHandle and useDebugValue. Another amazing thing is that you can make your own Reactjs hooks. You can build your own hooks which will let you extract component logic into reusable function. Customised hooks have become immensely popular as they add new features to the application and also simplifies tasks to a great extent.

It would be amazing if some you would go on to build your own customized hooks that leverages the power of Reactjs hooks to stir a positive change in the way we use and perceive technological applications.

Share your experience with Reactjs Hooks and tell us some interesting things that we might have missed. Also, if you reached here, we are sure you are an enthusiastic technocrat who would make a bright future in the world of web development and especially React.

Why Reactjs?

In this article, we’ve learnt about Reactjs hooks but the world of React has so much to offer. React is a booming technology and companies are constantly looking for React developers to upgrade their UI interface to render excellent experience for their users. React, that is essentially a Javascript library used for building UI interface, has a thriving potential in future. If you are crazy about web development and see yourself grow in this field then React is something that should definitely be a part of your stack of technical skills.

Konfinity ‘s Web Development Course will help you become a certified web developer and get a job of minimum 6 LPA by connecting you to our 200+ esteemed hiring partners like Google, Facebook, Classplus and Fashinza. It is trusted by students and graduates from IIT, DTU, NIT, Amity, DU and more.

Click here to start your trial.

Chat with us on WhatsApp