Hooks are a new addition in React 16.8. They allow you to have some state ( own storage ) and other React features without writing classes. They are really easy to use. We will see useState, useEffect Hooks, and we will also dive into creating our own custom Hooks, as well.

Table of Contents

  1. What are React Hooks?
  2. Rules of Hooks React
  3. React Hooks List
  4. UseState Hook React
  5. UseEffect React Hooks
  6. Custom React Hooks
  7. Conclusion

1. What are React Hooks?

Hooks allow us to “hook” into React features such as state and lifecycle methods. Because they work in functional react, you don’t really need classes. But that doesn’t mean that there is no need for classes. There is, and classes are still part of React.

2. Rules of Hook React

Hooks are similar to JavaScript functions, but you need to follow the rules when using them. These rules ensures that all the stateful logic in a component is visible in its source code.

Hooks can only be called at the top level of a component:

Hooks should always be used at the top level of the React functions. This rule ensures that Hooks are called in the same order each time a components renders.

Do not call Hooks inside loops, conditions, or nested functions.

Hooks can only be called inside React function components:

You cannot call Hook from regular JavaScript functions. Instead, you can only call Hooks from React function components. Or you can call Hooks from custom Hooks, as well.

ESLint Plugin

React’s create-react-app comes with an ESLint plugin called eslint-plugin-react-hooks that enforces these two rules.

3. React Hooks List

React comes with multiple hooks for you to use in your application. But in this article, we will see two Hooks that you are going to use most of the time.

  1. useState Hook
  2. useEffect Hook

4. UseState Hook React

UseState Hook allows you to define a state variable. It preserves some values between the function calls. We only need to provide an initial value to our state. It can be in the form of a number, a string, boolen, or even an array. UseState Hook contains two parameters: state variable and another variable to change the state value. You can give it any name you want. For example, if we need to store the number of times, a person clicks a button, we can name our useState variables as [count, setCount], so that we remember what it is actually doing.

import { useState } from "react";

const App = () => {

  const [count, setCount] = useState(0);
  const increaseCounter = () =>{
    setCount(prevCount=>prevCount+1)
  }
  const decreaseCounter = () =>{
    setCount(prevCount=>prevCount-1)
  }
  return (
    <div> 
      <h3>Counter : {count} </h3>
      <div>
        <button onClick={()=>increaseCounter()}>+</button>
        {count > 0 &&
        <button onClick={()=>decreaseCounter()}>-</button>
}
      </div>
    </div>
  )
};
export default App;

In the above code example, we have created a counter app, and initialized [count, setCount] to 0. We have two buttons. One increase the count and other decreases it. If the count variable is 0, it will only show button to increment the counter, and once counter value is > 0, it also shows decrement button to decrease the counter value.

useState Hook counter
useState Hook counter

You can use UseState multiple times, according to your requirements.

5. UseEffect React Hooks

The useEffect Hooks allows you to manage your side effects in your project. For example, if you want to render some data on page load, you can use UseEffect Hook. Or if you want to update your API fetched data, you can use UseEffect Hook to re-render your list, once your data gets updated.

UseEffect Hook accepts two arguments. First one is a function, and second one is an optional parameter that you can use. If you keep your second parameter empty, the useEffect will only once the page gets load for the first time.

For this tutorial, we will use a Random User API to get a random User, which we will display. Don’t worry, it will be a beginner friendly use of API in React.

import { useState, useEffect } from "react";

const App = () => {
  const [RandomData, setRandomData] = useState('');

  const getRandomUser = async()=>{
    const api = await fetch("https://randomuser.me/api/")
    const data = await api.json()  
    setRandomData(data.results[0])
  }
  useEffect(() => {
   getRandomUser()
 }, []);

  return (
    <>
    {RandomData && 
    <>
       <h1>Name : {RandomData['name'].first}</h1>
      <h2>Gender : {RandomData.gender}</h2>
      <h4>Email : {RandomData.email}</h4>
      <h4>Age : {RandomData['dob'].age}</h4>
      </>
    }
    
     </>
  );
};
export default App;

6. Custom React Hooks

Now that we have seen how to work with two most common Hooks of react, let’s dive into creating our very own Custom Hook. As the name suggest, you can code it to work in any way you want.

Custom Hook

React Hooks are reusable functions, which means you can use them for as many times as you want. Suppose that you have a functional logic that you need to use multiple times. Instead of copying pasting that again and again, you can put that logic in the form of a custom hook. Which means that you will be able to use it multiple times, without duplicating it.

To separate our custom hook from other functions, we are going to use “use” keyword before our Hook’s name. So, for this example, since we are pulling data from an API, we can call hook as “useFetch” hook. That way, it’s easier to remember and it’s using “use” keyword, so anyone else looking at our code, can understand that it is a custom hook.

Building the Hook

In our useEffect Hook code snippet, we pulled data from an API. Now, we will separate the same logic into our own hook.

Move your Hook to a new file

This fetch functionality can also be used in other components as well, so we are going to extract it into a custom Hook. To make it a custom hook, Copy the fetch logic, into another file, named useFetch.js.

useFetch.js

import { useState, useEffect } from "react";

const useFetch = (url) => {
    const [randomData, setRandomData] = useState('');

    const getRandomUser = async()=>{
        const api = await fetch(url)
        const data = await api.json()  
        setRandomData(data.results[0])
      }
      useEffect(() => {
       getRandomUser()
     }, [url]);

     return [randomData];

}

export default useFetch;

App.js

import useFetch from "./useFetch";

const App = () => {
  const [randomData] = useFetch('https://randomuser.me/api/') 

  return (
    <>
    {randomData && 
    <>
       <h1>Name : {randomData['name'].first}</h1>
      <h2>Gender : {randomData.gender}</h2>
      <h4>Email : {randomData.email}</h4>
      <h4>Age : {randomData['dob'].age}</h4>
      </>
    }
    
     </>
  );
};
export default App;

Explanation

We have created a new file named useFetch.js. It contains a function, useFetch which takes URL as an input, and fetches data from the API, using the URL provided. This makes it easier to use it multiple times, without having to duplicate the logic again.

Once it fetches data, it saves it in a useState variable, that we can use later.

In App.js, we are importing our useFetch Hook and using it like any other Hook. We also pass our dynamic URL in here too. As mentioned above, our custom hook, useFetch will fetch the data for us, which we can use here to display the data.

7. Conclusion

Now you should have a good understanding of what react hooks are. They are simple and easy to use, and allows you to hook into React’s features to manage your state and lifecycles method. This article also covers on creating your own custom hook. We saw how we can separate API data fetch logic into a hook, that we can use multiple times.

Related Articles:

Bootstrap with React
How to install React?

Leave a Reply

Your email address will not be published.