More

    React Hooks

     

    A hook is a component that allows us to use the features of React and state without defining a class. This feature is added from the React version 16.8 and further. This article covers a quick overview of React Hooks. This is a quick overview recommended for experienced React users. So, if you are new to React, you might find this confusing.

    State Hook

    This is an example of a counter that increments the value every time the button is clicked.

    import React, { useState } from 'react';
    function Example() {
     // Declare a new state variable, which we'll call "count"  const [count, setCount] = useState(0);
     return (
       <div>
         <p>You clicked {count} times</p>
         <button onClick={() => setCount(count + 1)}>
           Click me
         </button>
       </div>
     );
    }

    In the above example, useState is a hook that is called within a function component. This will add a local state to the Hook and React will conserve the state while re-rendering. The Hook named as useState returns a pair. This includes the value of the current state and a function form with which you can update the Hook. This is the same as this.setState used inside a class. The only difference is that it does not combine the new and old states.

    (A sample code differentiating useState to this.state is shown in the documentation of Using the State Hook)

    The initial state of the Hook is given as the argument to useState, and no other argument is mentioned. In the previous example, the argument of the Hook, useState, is ‘0’. This is because the counter begins with ‘0’. The initial state in the argument is only utilized when rendering is done for the first time.

    The state of a component is not necessarily to be an object, but if you want an object, then it can be the same. Whereas in this.state only objects can be used.

    Declaration of more than one state variable

    The state hook is compatible with multiple uses in an isolated component. The following code depicts this process.

    function ExampleWithManyStates() {
     // Declare multiple state variables!
     const [age, setAge] = useState(42);
     const [fruit, setFruit] = useState('banana');
     const [todos, setTodos] = useState([{ text: 'Learn Hooks' }]);
     // ...
    }

    The array destructuring syntax format is used for giving distinct names to the state variables we have declared. This is done through the useState Hook while calling it. But these states are not included in the useState API. In place of this React considers that you are calling it in the same order at every render when you are calling useState multiple times.  Its execution and use are explained in the further part of React.

    What is precisely a Hook?

    Hooks are React functions that can “Hook ” the state. Also, lifecycle features can be hooked from the functional components. The only thing to remember is that they do not work inside classes. Because they are meant to enable you to use reacting features without the need of declaring classes. React eases your job to an extreme level, but it doesn’t mean that you should start rewriting the components. Instead of re-coding the previous components, you can use hooks in the further program. If you have created a function component and you need to add a state to the component. For this, you would convert it into a class. But with hooks, you can hook the state inside the functional component.

    React has several built-in hooks like useState. But if you want some different logic to be used, you can create your own Hook. But initially, we will cover Built-in hooks only.

    The only disadvantage is that they create extra DOM parts. That consists of the nesting of the components that you have made.

    Effect Hooks

    In react you might have done a subscriptions program, data fetching, and changing the DOM from React components with a manual method. The procedures are known as “side effects”.  In the shorter term “effects”. The reason is that they affect the other components in the program and cannot be executed while rendering.

    useEffect is an effective hook. This allows you to perform all the side effect operations from a functional component. It works the same as the React functions componentDidMount, componentDidUpdate, and componentWillUnmount that are made in a class. The difference is that in Hook, all the functions are combined in a single API.

    The examples of useEffect Hook and other functions are shown in the documentation of Using the Effect Hooks.

    The below illustrator puts the title of the document after the DOM is updated by React.

    import React, { useState, useEffect } from 'react';
    function Example() {
     const [count, setCount] = useState(0);

    // Similar to componentDidMount and componentDidUpdate:  useEffect(() => {    // Update the document title using the browser API    document.title = `You clicked ${count} times`;  });
    return (
    <div>
    <p>You clicked {count} times</p>
    <button onClick={() => setCount(count + 1)}>
    Click me
    </button>
    </div>
    );
    }

    The useEffect Hook tells React to execute the effect function that has been made by you, after modifying the changes in the DOM. For having access to the state and props of the component, these hooks are defined in a component. After all the renders comprising the first render, React launches the effect hook.

    Effect Hooks also have the feature to clean up the DOM after their use through passing a function. The following example subscribes to a friend’s online status with the help of an effect in a component. After this, it cleans up by undoing the subscribe from the online status.

    import React, { useState, useEffect } from 'react';

    function FriendStatus(props) {
    const [isOnline, setIsOnline] = useState(null);

    function handleStatusChange(status) {
    setIsOnline(status.isOnline);
    }

    useEffect(() => {    ChatAPI.subscribeToFriendStatus(props.friend.id, handleStatusChange);    return () => {      ChatAPI.unsubscribeFromFriendStatus(props.friend.id, handleStatusChange);    };  });
    if (isOnline === null) {
    return ‘Loading…’;
    }
    return isOnline ? ‘Online’ : ‘Offline’;
    }

    In the sample code, React will undo the subscription from the chatAPI. This is done when the component is unmounted and before re-executing the effect hook in the following render. If the props.friend.id is not modified, then React will not follow the re-subscription program. Also, there are some hooks that do not require a clean-up of the DOM after their execution.

    As elaborated above, useeffect hook can be used numerous times in a component. Just like useState hook. The below illustration shows this:

    function FriendStatusWithCounter(props) {
     const [count, setCount] = useState(0);
     useEffect(() => {    document.title = `You clicked ${count} times`;
     });

    const [isOnline, setIsOnline] = useState(null);
    useEffect(() => {    ChatAPI.subscribeToFriendStatus(props.friend.id, handleStatusChange);
    return () => {
    ChatAPI.unsubscribeFromFriendStatus(props.friend.id, handleStatusChange);
    };
    });

    function handleStatusChange(status) {
    setIsOnline(status.isOnline);
    }
    // …

    With the help of effect hooks, you can manage the side effects happening in the components like subscribing and undoing the procedure. Whereas in the lifecycle process, you are required to follow split-based programming. If you want you can get to know more about useEffect Hook in the dedicated documentation of Using the Effect Hook.

    Rules for using Hooks

    It is mandatory to follow two rules while using them, even though they are Javascript functions.

    • Hooks are called only at the top, and they cannot be called inside a loop, conditioned statements, or nested functions.
    • Hooks are called through a React component only. They cannot be called from a normal Javascript component. (Another way for calling hooks is only in custom hooks)

    These rules may look confusing and restrictive, but they are essential for the functioning of hooks. If these rules are not followed, then there is no chance that your Hook will work properly. There is a linter plugin that takes care of the rules by applying them on its own. Such that you need not be concerned about them every time you write them.

    Creating Custom Hooks

    It is difficult to reuse stateful logic. For avoiding this problem, the traditional method is by creating higher-order components or render props. Instead of this, you can use custom hooks that allow you to use state hooks without the need of creating extra components in your structure.

    Previously we showed a sample code, that calls useState, and useEffect Hooks form a component named as FriendStatus. This code subscribes to the status of a friend. Assume that you need to use the same logic somewhere else. For this, we will create a custom hook and draw the login inside it. (useFriendStatus)

    import React, { useState, useEffect } from 'react';

    function useFriendStatus(friendID) {  const [isOnline, setIsOnline] = useState(null);

    function handleStatusChange(status) {
    setIsOnline(status.isOnline);
    }

    useEffect(() => {
    ChatAPI.subscribeToFriendStatus(friendID, handleStatusChange);
    return () => {
    ChatAPI.unsubscribeFromFriendStatus(friendID, handleStatusChange);
    };
    });

    return isOnline;
    }

    .

    This code makes FriendID as an argument and passes whether he is online or not. Now this logic can be used in any components.

    import React, { useState, useEffect } from 'react';

    function useFriendStatus(friendID) {  const [isOnline, setIsOnline] = useState(null);

    function handleStatusChange(status) {
    setIsOnline(status.isOnline);
    }

    useEffect(() => {
    ChatAPI.subscribeToFriendStatus(friendID, handleStatusChange);
    return () => {
    ChatAPI.unsubscribeFromFriendStatus(friendID, handleStatusChange);
    };
    });

    return isOnline;
    }

    .

    This code makes FriendID an argument and passes whether he is online or not. Now, this logic can be used in any component.

    function FriendStatus(props) {
     const isOnline = useFriendStatus(props.friend.id);
     if (isOnline === null) {
       return 'Loading...';
     }
     return isOnline ? 'Online' : 'Offline';
    }
    ----------------------------------------------------------------------------------------------------------------
    function FriendListItem(props) {
     const isOnline = useFriendStatus(props.friend.id);
     return (
       <li style={{ color: isOnline ? 'green' : 'black' }}>
         {props.friend.name}
       </li>
     );
    }

    The state is not dependent on any other component. Not only state hooks are convenient for utilizing the logic of stateful functions again and again. In addition, the same custom hook is able to be used several times in the components. Because it has its own individual state, whenever it is called.

    Custom Hooks are much more optimal than features. The custom hook syntax begins with ‘use’ that calls other hooks. The keyword ‘use’ signifies that the function is able to follow the rules of designing a hook. This syntax, followed by the name of the Hook helps the linter plugin to identify the bugs in the program utilizing hooks.

    Any logic can be described for a custom hook-like managing, counters, transitions, declarative logic, etc. We are eager to find out what logic you will use.

    Other Hooks

    There are some hooks that are inbuilt but are not used quite often. But these are very helpful while programming. One of them is useContext. This allows taking a subscription of a React context, ignoring the requirement of nesting. The following is a sample code for your convenience.

    function Example() {
     const locale = useContext(LocaleContext);  const theme = useContext(ThemeContext);  // ...
    }

    .

    useReducer is another such hook that can be helpful. With this, you can direct the local state of the complicated component (ignoring the need for a reducer).

    Here’s is an example for the useReducer hook:

    function Todos() {
     const [todos, dispatch] = useReducer(todosReducer);  // ...

    Further Procedure

    This was a quick summary of React Hooks. That covered all the necessary information that you will need to understand Reactive Hooks. In addition to the above additional hooks, several more hooks are less used. They make your code look much organized and clean. With the minimal use of components, Hooks save a considerable amount of time. Also, they are efficient in the testing procedure.

    Recent Articles

    React Fragment: Find out what we encountered.!

      React Fragment: Hello Devs, in my journey of learning react I came across some frontend conditions where I had to render multiple react components,...

    React Admin: Documentation | Features | Dahboard | Templates

      React Admin is a framework for the front-end development of data-driven applications. That is operating in a browser over the top of REST or...

    React Hooks

      A hook is a component that allows us to use the features of React and state without defining a class. This feature is added...

    React Animation: A definitive guide

    React Animations Add-ons The ReactTransitionGroup add-on is a lower-level Applications Program Interface (API) component for creating react animations. And the ReactCSSTransitionGroup, is a component used...

    Create React App: A Complete guide for Beginners

      Create React App is the modern way of building an official Single Page React Application. It sets up a comfortable environment for building react...

    Related Stories

    Leave A Reply

    Please enter your comment!
    Please enter your name here