Introducing React Hooks

Hooks are a new addition in React 16.8. A Hook is a special function that lets you “hook into” React features. Hooks let you use state and other React features inside functional components without writing a class component. I'm assuming you already know about react , functional component and class component .

React Hooks start with 'use' keyword prefix e.g. useState, useEffect and we can also create our own custom hooks too with 'use' keyword as a prefix so that it will follow the rules of Hooks that we will discuss at the end of this.

Before we continue, read these facts about Hooks:

Completely opt-in : You can try Hooks in a few components without rewriting any existing code. But you don’t have to learn or use Hooks right now if you don’t want to.

100% backward-compatible : Hooks don’t contain any breaking changes.

Hooks don’t replace your knowledge of React concepts : Instead, Hooks provide a more direct API to the React concepts you already know: props, state, context, refs, and lifecycle.

Why We Need Hooks?

  • Classes confuse both people and machines : In complex applications, you create a functional component for stateless component or as a presentational component so that there is no functionality related to the state and for the stateful component, we create a class component. But if later you are required to add state in a functional component then you have to change it to a class component. For bigger applications, it is a very long process in making changes to the existing code. The distinction between function and class components in React and when to use each one leads to disagreements even between experienced React developers.

    Classes can be a large barrier to learning React. If you know about arrow functions then you must know in events this keyword doesn't point to that element but inside arrow function , it will point to that function inside which we are using this keyword . You have to understand how this works in JavaScript, which is very different from how it works in most of the languages. You have to remember to bind the event handlers.

    Classes present issues for today’s tools, too. For example, classes don’t minify very well, and they make hot reloading flaky and unreliable.

We can solve this using Hooks

  • It’s hard to reuse stateful logic between components : Traditionally in React, we’ve two popular ways to share stateful logic between components: render props and higher-order components. When we want to share logic between two JavaScript functions, we extract it to a third function. Both components and Hooks are functions, so this works for them too!. Hooks solve many of the same problems without forcing you to add more components to the tree.

    A custom Hook is a JavaScript function whose name starts with ”use” and that may call other Hooks. Unlike a React component, a custom Hook doesn’t need to have a specific signature. We can decide what it takes as arguments, and what, if anything, it should return. In other words, it’s just like a normal function. Its name should always start with use so that you can tell at a glance that the rules of Hooks apply to it.

We can solve this by creating a Custom Hook

  • Complex components become hard to understand : Inside class component, we have to maintain many functions of the lifecycle like fetching in componentDidMount and componentDidUpdate. Checking of updates in shouldComponentUpdate and componentDidMount will contains all functions related to event handlers and for cleanup, we used componentWillUnmount. Each lifecycle method often contains a mix of unrelated logic. Related functionality should be in one function and unrelated code should be indifferent ones but this is not in case of lifecycle methods. This makes it too easy for bugs and logical errors.

    So here comes Hooks that helps us to write everything in functional component without thinking much about which component should be class component or which should be a functional component.

We can solve this using useEffect Hook

Now, let the game of Hooks begin

Here, we will go through the most used hooks to give you an idea about how to use Hooks and we will discuss them in detail in my next blog.

  • State Hook: In react till now we are managing the internal state using this.setState and classes are not a need anymore. So we will use now most important React Hook: useState. useState is a function exposed by the react package. You will import that function at the top of your files as:

       import React, { useState } from "react";
    

    Now we will see how we use this hook -

       const inputObject = useState({title: 'React Hooks'});
    

    You might be thinking that we have created state here but how we will change this state and what useState is returning and can be pass only object inside useState?

  • Effect Hook: You’ve likely performed data fetching, subscriptions, or manually changing the DOM from React components before. We call these operations “side effects” because they can affect other components and can’t be done during rendering.

       import React, { useEffect } from "react";
    

    The Effect Hook, useEffect, adds the ability to perform side effects from a function component. It serves the same purpose as componentDidMount, componentDidUpdate and componentWillUnmount in React classes, but unified into a single API.

      useEffect(() => {
      fetch("url")
        .then(response => response.json())
        .then(data => setData(data));
    });
    

    You might be thinking that how we are handling all the lifecycle methods using only one function useEffect.

  • Other Hook: There are a few commonly used built-in Hooks that you might find useful. For example, useContext lets you subscribe to React context without introducing nesting

       import React, { useContext } from "react";
       const locale = useContext(LocaleContext);
    

    useReducer,useCallback, useMemo these are other hooks available too.

All these questions that are coming in your mind we will discuss them in my next blog

Rules of Hooks

Hooks are JavaScript functions, but they impose two additional rules:

  • Only call Hooks at the top level. Don’t call Hooks inside loops, conditions or nested functions.

  • Only call Hooks from React function components or your own custom hooks. Don’t call Hooks from regular JavaScript functions and class components.

    Reason For this

    We can use multiple State or Effect Hooks in a single component. So how does React know which state corresponds to which useState call? The answer is that React relies on the order in which Hooks are called.

    This is why Hooks must be called on the top level of our components. If we want to run an effect conditionally, we can put that condition inside our Hook.

Thanks For Reading ...

If anything is wrong here by mistake do let me know. I will read it further and make changes accordingly.

Please like it if it helped you in anyway or comment if you have any doubts regarding this or want to give some suggestions.

P.S. Follow me on LinkedIn and Twitter for more updates.