Build your own Custom Hooks

Introduction

So if you are wondering about creating your customized hooks, let’s brief what hooks in react are?

Hooks in React allows you to hook into the react state and lifestyle features through the function component. Let’s see how we can create a component using a Hook in ReactJs.

 

import React, { useState } from "react";

function App() {
 const click = useState("Coding Ninjas");
 return <h1>We welcome you to {click}</h1>;
}

export default App;

 

OUTPUT

 

 

The above code is a simple example of how we can create a react hook. Moving on, now we have seen what hooks are and an example related to them. Well, there is much more to it. Let’s take a look at the bare hooks and their models. Want to learn more about hooks before moving with creating your hooks? Don’t worry, we got you. Give this Hooks at Glance blog a read to be ready with all the information you will need.  Well, this article will help you understand how you can create your hooks. Interesting, isn’t it? Building our hooks would allow us to extract different component logic into reusable functions. Let’s understand what Custom Hooks are and how we can create them. 

 

 

What are Custom Hooks?

In ReactJs, there might be times when we have been writing the same repetitive code with redundant stateful logic inside the multiple components. If we try to reuse the code and build it for the same reason, this could be done using render props and high-order components in the case of class components. Well, the function components allow a much easier and cleaner way to tackle this problem, that is, by allowing you to create your custom hooks. 

Custom Hooks hold certain logic and are similar to the functions but their names start with the keyword ‘use’. 

 

If we brief out the above explanation, we can say that the custom hooks allow you to extract existing components and use them in your application. 

 

Let’s go through some interesting examples that you can create as a custom hook and implement in your application.

Build your Custom Hooks

Custom hooks are general essential functions with the keyword “use” before their identifier.  The customized hook is just like a regular function, and the word "use" in the beginning tells us that this function follows the rules of Hooks. Building custom Hooks allows us to extract component logic into reusable parts.

Let’s try to create our custom hook to understand it better. 

In this article, we will create some custom hooks, to help you understand. After going through these examples, we hope you will be able to create your custom hooks!

 

Create a Custom Hook to calculate window size

 

import { useState, useEffect } from "react";
function App() {
 const size = useWindowSize();
 return (
  <div>
    {size.width}px / {size.height}px
  </div>
);
}

function useWindowSize() {
 const [windowSize, setWindowSize] = useState({
  widthundefined,
  heightundefined,
});
useEffect(() => {
  
  function handleResize() {
    
    setWindowSize({
      widthwindow.innerWidth,
      heightwindow.innerHeight,
    });
  }
  window.addEventListener("resize", handleResize);
  
  handleResize();

  return () => window.removeEventListener("resize", handleResize);
}, []);
 return windowSize;
}
export default App;

 

OUTPUT

 

 

In the above example, we have a hook that returns the size of the current window. Let’s see what the logic of the hook is - When we make a call to this hook, the first thing it will do is get the size of the current window to return it. Second, it will attach the event listener to the window’s object and it will listen to resize the event. When the event happens, the hook would detect the window’s new size and return it. This would be repeated every time whenever the resize event happens. Custom hooks can use the other React hooks. We can use the useState hook to store the latest window size in a state and return the value of this state. We can also use the useEffect hook to attach the event listener for resizing events.

Create a Custom Hook to useLocalStorage

import { useState } from "react";
function App() {
 const [name, setName] = useLocalStorage("name""Bob");
 return (
  <div>
    <input
      type="text"
      placeholder="Enter your name."
      value={name}
      onChange={(e) => setName(e.target.value)}
    />
  </div>
);
}
function useLocalStorage(key, initialValue) {
 // State to store our value.
 // Pass initial state function to useState, so logic is only executed once.
 const [storedValue, setStoredValue] = useState(() => {
  try {
    // Get from local storage by key.
    const item = window.localStorage.getItem(key);
    // Parse stored json or if none return initialValue.
    return item ? JSON.parse(item) : initialValue;
  } catch (error) {
    // If errors also return initialValue.
    console.log(error);
    return initialValue;
  }
});

 const setValue = (value) => {
  try {
    const valueToStore =
      value instanceof Function ? value(storedValue) : value;
      setStoredValue(valueToStore);
          window.localStorage.setItem(key, JSON.stringify(valueToStore));
  } catch (error) {
        console.log(error);
  }
};
 return [storedValue, setValue];
}
export default App;

 

OUTPUT

       

This hook will accept two parameters: 

  •  the name of the key to store and the initial value for this hook. When this hook is called, it will first check local storage available in the browser. If the local storage isn't public, it will return the initial value passed as an argument. If the local storage is available, the hook will check any key with the same name. If we do find a legend with the same name, the hook will retrieve its data. Otherwise, the hook will simply return the initial value. Whatever value is returned will be the state of the hook. It will happen inside the initializer function for the useState hook. 
  •  The second part of the hook is a handler function used to store data in local storage. This function accepts only one parameter,  that is, the data to store. The function will take this value and keep it in the hook state. Then, it will hold the value in the local storage of the browser. The name of the key for this data will be the name of the key passed to the hook during the call. The last part, returning something. 
  • This hook will return two things: the current value of the state, data loaded from local storage, and the handler function for storing data in local storage.

 

We have already seen by this far-away that the officially react hooks cannot do everything on their own, so we have the power to create our custom hooks, to make our tasks more accessible and the code cleaner. For developers, building custom hooks is equivalent to creating an Art. Are you interested in more? Why not make it? Still, every them yourself!

We have a few curated most asked questions about Custom Hooks. Let’s go through them. 

Frequently Asked Questions

  1. What is a Custom Hook in React?
    Ans: Custom hooks are general essential functions with the keyword “use” before their identifier.  The customized hook is just like a regular function, and the word "use" in the beginning tells us that this function follows the rules of Hooks. Building custom Hooks allows us to extract component logic into reusable parts, but every time we use a custom Hook, all states and effects inside of it are fully isolated.

     
  2. If the two components share the same hook, would they share the same state?
    Ans: No. Custom Hooks are a method that is used to reuse stateful logic (such as setting up a subscription and remembering the current value). Still, whenever we use a custom Hook, all states and effects inside it get fully isolated.

     
  3. How does a custom hook get an isolated state?

    Ans: In React, Each call to a Hook takes us into an isolated state. This is because when we call a custom hook directly, our component just calls state and useEffect. We can call useState and useEffect any number of times in one component, and they will be completely independent.

     
  4. How are custom hooks different from general functions?

    Ans:  A custom hook is a function that follows the rules of hooks, just like built-in hooks. Since the custom hooks typically contain hooks themselves, we have to make sure our custom hooks are only called where it is legal to use hooks generally. The difference between a general function and a custom hook is that the custom hooks start with the keyword ‘use’. 

Key Takeaways

Hey everyone, so let’s brief out the article. Let’s discuss in brief whatever we have discussed here. 

  • Hooks in React allows you to hook into the react state and lifestyle features through the function component. Hooks are a new feature update of the React in version 16.81. Hooks allow us to use the functionality of various states and React features without using the class.
  • After discussing the basics of hooks, we have gone over each type of hook using an example, and the fantastic feature is that you can create your custom Hooks by just using the “use” keyword before declaring a function.
  • We have discussed various examples of implementing our custom hooks and using them along with the available default hooks. Remember that the sky's the limit, and we hope that your basics are clear, and now you are ready to create your magical custom hooks in React.

 

Isn’t Web Development engaging? Building new websites and using amazing animations and different APIs, don’t be scared if you cannot grasp the hold of this vast development. We have the perfect web development course for you to make you stand out from your fellow developers. 

 

Happy Learning Ninjas!

 

By: Rubleen Kaur

 

Was this article helpful ?
0 upvotes

Comments

No comments yet

Be the first to share what you think