King Somto
4 Jan 2023
•
5 min read
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>
);
}
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.
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?
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 >
) } />
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.
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.
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
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. Looking good right? now we have an app that lets us see the latest prices of our best crypto tokens.
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.
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.
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.
Ground Floor, Verse Building, 18 Brunswick Place, London, N1 6DZ
108 E 16th Street, New York, NY 10003
Join over 111,000 others and get access to exclusive content, job opportunities and more!