We're planting a tree for every job application! Click here to learn more

Ever wanted to build a custom react hook?

King Somto

4 Jan 2023

•

5 min read

Ever wanted to build a custom react hook?
  • JavaScript

What are React hooks?

React hooks are functions in react stateless components that let you create and update a state without having to use class components, when building React frontend apps using functional or stateless components is usually preferred over class components for smaller Components.

Let's look at an example.

import React, { useState } from 'react';
function StatelessCount( ) {
  const [ count , setCounter ] = useState( 0 );
  return (
    <div>
      <p>You clicked me {count} times</p>
      <button onClick={ () => setCounter( count + 1 ) }>
        Click me, please!
      </button>
    </div>
  );
}

What are custom react hooks?

While building React applications at scale, we need to share logic among components, an example would be we want a couple of components to be aware of a certain change in an app, a direct example would be building a social media application and we want to let multiple components on a friends list page or friend page know if a user is online so we can render a different view to our user, making that logic in each component would be hard and clunky mainly because that logic can always change later during the development of the application, so we would like to do it one time in an isolated place that I can be edited or changed and imported into our components.

Before we look at custom hooks let's look at 2 other ways of doing this, they both are higher-order components and render props.

Higher order components

With a higher-order component, we share the logic by wrapping our component inside another component and updating the HOC component which causes the reRendering of the component when there is a trigger.

Taking an example would be

import React from "react";
import { isFriendOnline }  from './services'

const UserOnlineComponent = ( PassedComponent ) => {
 function HOComponent ( props ) {
const [ online , setOnline ] = React.useState( false )
React .useEffect( ()=> {
	//check if a user is online every 2 seconds
	 const intervalId = setInterval( ()=>{
		setOnline( isFriendOnline() )
	} , 2000 )

	return  () => { 
			clearInterval(intervalId) ; /// clear interval function to cleanup
		};
} , [] )
  //render passed components and pass on props
    return <PassedComponent online = {online} />;
  }
  return HOComponent;
};
export default UserOnlineComponent;

Breaking it down

	//check if a user is online every 2 seconds
	 const intervalId = setInterval( ()=>{
		setOnline( isFriendOnline() )
	} , 2000 )

Here we check our component every 2 seconds to see if they are online then update the status of the friend by setting the online prop to true

Components can be used like

import React from "react";

const Components = ( props ) => {
 	return <div> this user is {props.online?' online ' : ' not online '} </div>
  }

Every component can now have a prop that tells it when a friend is online, but how to create a higher Order component to implement it all we have to do is

const Component = UserOnlineComponent( ComponentWithoutProp )

Other places to learn about Higer order components What are the different ways in which React HOC components can be defined?

Render Props

The term Render props refers to a way of sharing code between components using props whose value is a function.

< DataProvider render={ data => (
 <h1> Hello { data.target } </h1 >
) } />

Why use Custom react hooks over other options

The main use of custom react hooks is reusability which enables components to reuse logic without actually rewriting the code, react custom hooks also can rerender the components to apply those changes which are similar to other options available, custom react hooks are cleaner and easier to use than both higher-order components or render props.

Advantages of using custom react hooks

Using custom React hooks in many cases helps us not have to rebuild logic in every single one of our components, but it also has a lot more advantages namely.

  • Easier to use and understand code also passing parameters into it to make it more dynamic is much more straightforward than the alternatives.
  • It is optimized and scalable
  • Reduces less redundant code
  • Optimized format
  • Re-renders view

Rules for using React Hooks

A custom hook in React is a function that begins with the use of the word use and can call other hooks inside it like useEffect and useState an example would be useMe, this naming convention is mainly used to help the linter find bugs in its usage, a common example would be scenarios where it violates the react Hook rules.

Other major rules are

  • Only call react hooks in the top level Do NOT !!!! I mean do NOT !!! call Hooks inside loops, conditions, or nested functions, mainly inside loops ( you may cry ).
  • Hooks should only be called from React function components.
  • Hooks should not be called from regular JavaScript functions. (There is only one other place where you can call Hooks — your custom Hooks. We'll learn more about them shortly.)

Building a simple custom react hook

For this part of the article, I had to figure out a simple application for a react hook example that was simple and practical at the same time, so I settled on building a crypto application that monitors the crypto prices in USD and shows those prices and changes every 2 seconds.

To start your application run the following code

 npx create-react-app cryptocheck 

then

cd cryptocheck and npm run start 

Now have our react application, next we would attempt making our hook simply create a new file call it whatever you like.

touch whateveryoulike.js

Paste the following inside

import React from " react ";

const Hook = (token = "BTC") => {
  const [ data, setData ] = React.useState( null );

  React.useEffect( () => {
    const interval = setInterval(async () => {
      ////// check for prices every 2 seconds
      fetch(
        `https://api.binance.com/api/v3/ticker/price?symbol=${ token.toLocaleUpperCase()}USDT`
      )
        .then( (res) => res.json ( ) )
        .then( ( { price } ) => setData ( price ) );
    }, 2000);

    return ( ) => {
      clearInterval( interval ) ;
    } ;
  } , [ token ] ) ;

  return data ;
};

export default Hook;

That's our complete custom React hook breaking it down into the major bits we have.

 React.useEffect( () => {
    const interval = setInterval(async () => {
      ////// check for prices every 2 seconds
      fetch(
        `https://api.binance.com/api/v3/ticker/price?symbol=${ token.toLocaleUpperCase()}USDT`
      )
        .then( (res) => res.json ( ) )
        .then( ( { price } ) => setData ( price ) );
    }, 2000);

Here we use useEffect to instantiate a setInterval command that can periodically check the binance API every 2 seconds and call the setData function that sets the new data.

   return ( ) => {
      clearInterval( interval ) ;
    } ;

Basic clean up of our interval so we won't have problems.

So now we have built out our hook, but how do we use it?

Well something as simple as this

  const priceMatic = useCryptoHook("matic");

Don't believe me do you? , I get it let's look at it in code then.

import  " ./styles.css " ;
import useCryptoHook from " ./whateveryounamedthefile " ;
export default function App ( ) {
  const priceBtc = useCryptoHook( ) ; ///default is BTC so no need to actually pass BTC
  const priceEth = useCryptoHook( "eth" ) ;
  const priceMatic = useCryptoHook( "matic" ) ;
  return (
    <div className = "App" >
      <h1> Hello CodeSandbox </h1>
      <h2>current price of BTC ${priceBtc} </h2>
      <h2>current price of eth ${priceEth} </h2>
      <h2>current price of eth ${priceMatic} </h2>
    </div>
  ) ;
}

Now let's see our output. Screen Shot 2022-12-31 at 12.39.47 PM.png Looking good right? now we have an app that lets us see the latest prices of our best crypto tokens.

Smart ways to use React hooks

React hooks are mainly used in places where we want to reduce complexity and code and at the same time isolate logic into a single component that can be isolated and tested on its own.

Horrible ways to use hooks

I personally advise you to use custom react hooks inside smaller components because they do cause the rerendering of the entire component so if you do place the react custom hook inside a top-level component and that hook is rendered a couple of times it would cause that component to rerender and make the application a bit slower, but for a simple case like our its perfect.

Conclusion.

Custom react hooks are an amazing way of isolating reusable logic and using them across multiple select components in our application while avoiding complexity, I found usehooks to be an amazing resource for learning about react hooks you can also check out the react documentation page for more examples and applications of react hooks. Overall custom React hooks can be expanded upon to add more complex functionality and also make use of some other React hooks like useReducer, ' useHistory ' etc.

Did you like this article?

King Somto

Dev

See other articles by King

Related jobs

See all

Title

The company

  • Remote

Title

The company

  • Remote

Title

The company

  • Remote

Title

The company

  • Remote

Related articles

JavaScript Functional Style Made Simple

JavaScript Functional Style Made Simple

Daniel Boros

•

12 Sep 2021

JavaScript Functional Style Made Simple

JavaScript Functional Style Made Simple

Daniel Boros

•

12 Sep 2021

WorksHub

CareersCompaniesSitemapFunctional WorksBlockchain WorksJavaScript WorksAI WorksGolang WorksJava WorksPython WorksRemote Works
hello@works-hub.com

Ground Floor, Verse Building, 18 Brunswick Place, London, N1 6DZ

108 E 16th Street, New York, NY 10003

Subscribe to our newsletter

Join over 111,000 others and get access to exclusive content, job opportunities and more!

© 2024 WorksHub

Privacy PolicyDeveloped by WorksHub