DEV Community

shahabbukhari
shahabbukhari

Posted on

React Custom Hooks Simplified

When you build any application Hooks are the most commonly utilized thing, Hooks like useState, useEffect, or useRef are the most common ones but sometimes they are not enough you need to write your own custom hooks

A Bit of History:

Not a long before everything in react was classes and It has been approximately one year since React v16.8 was released, marking the introduction of Hooks. They let you use state and other React features without writing a class.

https://y.yarn.co/ca6ccdca-b805-477f-838e-529abd024b29_text.gif

Hooks make React so much better because you have simpler code that implements similar functionalities faster and more effectively. You can also implement React state and lifecycle methods without writing classes.

Let’s see the comparison of class-based components vs functional components.

// Class Based
import "./styles.css";
import React from "react";

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      count: 0
    };
  }
  clickHandler = () => {
    this.setState((prevState) => ({
      count: prevState.count + 1
    }));
  };

  render() {
    return (
      <div>
        <button onClick={this.clickHandler}>Click To Count</button>
        {this.state.count}
      </div>
    );
  }
}

export default App;
Enter fullscreen mode Exit fullscreen mode
// functional components
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>
  );
}
Enter fullscreen mode Exit fullscreen mode

After React v16.8 one thing was clear now we won’t have to write more classes functions are the future.

Classes Vs Functions

Custom Hooks:

In simple words, the custom hook is just a functional running inside a component. they use other hooks based on the type of functionality they are providing. custom hooks are so powerful and help you minimize the complexity by creating a level of abstraction and making your code much cleaner and reusable.

In this blog/tutorial we will be creating a progress bar with the custom hook of useCounter.

Note: using **use** before a hook is a convention. after all it's just a function Its name should always start with use so that you can tell at a glance that the rules of Hooks apply to it.

Progress Bar:

Let's see I wanted to build a progress bar component that will get completed in a specified amount of time. for that, I will need some sort of a variable whose value increase after every second and stops after a specified.

Untitled

Counter Custom Hook:

Let’s first create a counter hook that will return a value that will get updated after every second.

// 📁 Timer.js
import { useState, useEffect } from "react";

function useCounter(start, end) {
  const [reach, setReach] = useState(start);

  useEffect(() => {
    let myInterval = setInterval(() => {
      setReach((prev) => {
        if (prev === end) clearInterval(myInterval);
        return ++prev;
      });
    }, 1000);
  }, []);

  return reach;
}

export default useCounter;
Enter fullscreen mode Exit fullscreen mode

As a said before hooks are just the fancy name for javascript functions. In the above code first, we have created a reach state which tells us where the counter has reached or at which value it's at. and then we have useEffectit runs only one’s and run a setInterval function which takes a callback as a parameter inside we have our setReach function which increments a previous value after each second and when it hits the limit it calls the clearInterval function which stops the interval. And in the end, we return the reach variable to use in other components.

More on setInterval here*

How to use a Custom Hook:

We can use our useCounter hook the same as any other hook inside our react application. for the progress bar, we will use HTML's own progress tag to represent the progress.

More on progress tag here

// 📁 App.js
import useCounter from "./Timer";

export default function App() {
  let count = useCounter(0, 60);

  return (
    <progress value={count} max="60">
      {" "}
    </progress>
  );
}
Enter fullscreen mode Exit fullscreen mode

useCounter requires two parameters one for the initial value where to start and one is for where to end.

Conclusion

That's pretty much it's about creating your own custom hooks in react custom hooks are just functions and they are easier than you think. Custom React hooks can give us the tools to fix our own problems when third-party libraries fall short.

Also, react-use is also a very useful library that provides bundles of custom hooks that you can use in your application. Right out of the box you get so many custom hooks ready to use. Which has hooks for sensors, UI, animation, states, and many more. do check that out.

I hope this guide helps you in some way. If it did leave a comment follow my profile for more content like this or you read some of my other articles and if you have any confusion ping me on Linkedin.

THANKS FOR READING

Top comments (0)