• Mail us
  • Book a Meeting
  • Call us
  • Chat with us

ReactJS

What Does the type Attribute Do in a <script> Tag?


Introduction

With hooks, React has truly changed the nature of web development for developers: you can finally use state and other React features without needing to write a class. But apart from all those built-in hooks like useState, useEffect and useContext, the library also empowers you to create your very own custom hooks to encapsulate reusable logic.

This makes it so whenever you have component logic that needs to be used across multiple components, we can extract that to a custom hook.

What Are Custom Hooks?

A custom hook is a function that can call other hooks and include any business logic your application requires. It has to follow the rules of hooks for example, it should only be called at the top level of a functional component or within another hook.

 

Why Use Custom Hooks?

Custom hooks make your codebase cleaner by encouraging reusability and separation of concerns. Here are a few benefits:

  • Reusability: Encapsulate logic that's used across multiple components.
  • Cleaner Components: Reduce the complexity of functional components by moving logic to a hook.
  • Abstraction: Hide implementation details, making components easier to understand and maintain.
  • Testability: Isolate logic for easier unit testing.
  •  

Basic Example

Let's take a step into creating a custom hook for managing a counter. In this hook, we will have state management logic that encapsulates the incrementation, decrementing and reset of a counter.

Step 1: Define the Custom Hook

import { useState } from 'react';function useCounter(initialValue = 0) { const [count, setCount] = useState(initialValue); const increment = () => setCount((prev) => prev + 1); const decrement = () => setCount((prev) => prev - 1); const reset = () => setCount(initialValue); return { count, increment, decrement, reset };}export default useCounter;

 

Step 2: Use the Hook in a Component

import React from 'react';import useCounter from './useCounter';function CounterComponent() { const { count, increment, decrement, reset } = useCounter(0); return ( <div> <h1>Counter: {count}</h1> <button onClick={increment}>Increment</button> <button onClick={decrement}>Decrement</button> <button onClick={reset}>Reset</button> </div> );}export default CounterComponent;

 

Real World Example: Fetching Data

Let's create a hook called useFetch to encapsulate logic for fetching and managing API data.

Step 1: Define the useFetch Hook

import { useState, useEffect } from 'react';function useFetch(url) { const [data, setData] = useState(null); const [loading, setLoading] = useState(true); const [error, setError] = useState(null); useEffect(() => { let isMounted = true; setLoading(true); fetch(url) .then((response) => { if (!response.ok) { throw new Error('Failed to fetch data'); } return response.json(); }) .then((data) => { if (isMounted) { setData(data); setLoading(false); } }) .catch((err) => { if (isMounted) { setError(err.message); setLoading(false); } }); return () => { isMounted = false; }; }, [url]); return { data, loading, error };}export default useFetch;

 

Step 2: Use the useFetch Hook

import React from 'react';import useFetch from './useFetch';function UsersList() { const { data, loading, error } = useFetch('https://jsonplaceholder.typicode.com/users'); if (loading) return <p>Loading...</p>; if (error) return <p>Error: {error}</p>; return ( <ul> {data.map((user) => ( <li key={user.id}>{user.name}</li> ))} </ul> );}export default UsersList;

 

Conclusion

Custom hooks are a powerful way to share logic across your React components. Encapsulating complex or repetitive logic into reusable functions keeps your components clean, maintainable and focused on their primary purpose.

 

Ready to transform your business with our technology solutions? Contact Us today to Leverage Our ReactJS Expertise.

0

Share

facebook
LinkedIn
Twitter
Mail
React

Related Center Of Excellence