In React, components often share similar logic, such as fetching data or handling form inputs. Instead of repeating this logic across multiple components, we can extract it into a custom hook. But what exactly are custom hooks, and how do they help?
What Are Custom Hooks?
A custom hook is a JavaScript function that starts with use and internally calls other hooks like useState, useEffect, or useContext. It allows developers to extract reusable logic, keeping components clean and modular.
Syntax
function useCustomHook() {
// Use built-in hooks here
return someValue;
}
Steps to Create a Custom Hook
1. Define a Function That Starts with use
Custom hooks must follow React's naming convention and start with use (e.g., useFetch). This ensures React recognizes it as a hook and enforces hook rules.
function useCustomHook() {
// Hook logic here
return someValue;
}
2. Use React's Built-in Hooks Inside Your Custom Hook
Custom hooks can use useState, useEffect, useContext, etc., to manage state, handle side effects, or access context.
function useCounter() {
const [count, setCount] = useState(0);
return [count, () => setCount(count + 1)];
}
3. Add Logic Inside useEffect for Side Effects
If your custom hook performs side effects (e.g., fetching data, subscribing to a service), use useEffect to control when the effect runs.
function useFetchData(url) {
const [data, setData] = useState(null);
useEffect(() => {
fetch(url).then(response => response.json()).then(setData);
}, [url]);
return data;
}
4. Return Necessary Values
Your custom hook should return state, functions, or values that components need, such as fetched data, loading state, or error messages.
function useToggle(initialValue = false) {
const [state, setState] = useState(initialValue);
const toggle = () => setState(prev => !prev);
return [state, toggle];
}
5. Use the Custom Hook in Components
Once defined, your custom hook can be used inside a React component just like a built-in hook.
function ExampleComponent() {
const [isOn, toggle] = useToggle();
return <button onClick={toggle}>{isOn ? "ON" : "OFF"}</button>;
}
Implementing A Custom Hook
1. Creating a Custom Hook for Fetching Data
Custom hooks can be used for handling the API requests.
JavaScript
import { useState, useEffect } from 'react';
function useFetch(url) {
const [data, setData] = useState(null);
const [loading, setLoading] = useState(true);
useEffect(() => {
fetch(url)
.then((response) => response.json())
.then((data) => {
setData(data);
setLoading(false);
});
}, [url]);
return { data, loading };
}
function DataComponent() {
const { data, loading } = useFetch("https://jsonplaceholder.typicode.com/todos/1");
return (
<div>
{loading ? <p>Loading...</p> : <p>Data: {JSON.stringify(data)}</p>}
</div>
);
}
export default DataComponent;
Output
Creating a Custom Hook for Fetching DataIn this example
- useFetch is the custom hook.
- useFetch encapsulates API-fetching logic, making it reusable.
- Components using useFetch don't have to implement fetching logic themselves.
2. Creating a Custom Hook for the Save Button with Online/Offline Status
This example consists of a custom hook (useOnlineStatus) that tracks the online/offline status of a user and a React component (SaveButton) that uses this custom hook to enable or disable a button based on the network status.
JavaScript
//src/App.js
import useOnlineStatus from './useOnlineStatus';
export default function SaveButton() {
const isOnline = useOnlineStatus();
function handleSaveClick() {
console.log('✅ Progress saved');
}
return (
<button disabled={!isOnline} onClick={handleSaveClick}>
{isOnline ? 'Save progress' : 'Reconnecting...'}
</button>
);
}
JavaScript
//src/useOnlineStatus.js
import { useState, useEffect } from 'react';
function useOnlineStatus() {
const [isOnline, setIsOnline] = useState(navigator.onLine);
useEffect(() => {
function handleOnline() {
setIsOnline(true);
}
function handleOffline() {
setIsOnline(false);
}
window.addEventListener('online', handleOnline);
window.addEventListener('offline', handleOffline);
return () => {
window.removeEventListener('online', handleOnline);
window.removeEventListener('offline', handleOffline);
};
}, []);
return isOnline;
}
export default useOnlineStatus;
Output
In this example
- useOnlineStatus hook tracks the user's internet connection status using useState and useEffect. It listens for online and offline events and updates the state accordingly.
- This component imports the useOnlineStatus hook to determine whether the user is online. If offline, the button is disabled and displays "Reconnecting...". If online, the button is enabled with "Save progress."
- The useEffect inside the custom hook adds event listeners for network status changes and cleans them up when the component unmounts to prevent memory leaks.
- useOnlineStatus is a custom hook because it encapsulates the logic for checking internet status and can be reused across multiple components.
When to Use Custom Hooks
You should use custom hooks when
- We need to reuse logic across multiple components.
- We want to improve readability and maintainability by keeping component logic clean.
- We are using multiple built-in hooks together in a reusable way.
- We want to encapsulate side effects like data fetching or state management
Interesting Things About Custom Hooks
- Reusability Across Components: Custom hooks are designed to be reusable. They allow you to extract logic from components so the same functionality can be shared between different parts of your app without repeating code.
- Encapsulates Logic: Custom hooks encapsulate logic in a reusable way, keeping your components cleaner and more focused on UI rendering. This is especially useful for managing side effects, API calls, or complex state logic.
- Can Return Multiple Values: A custom hook can return multiple values (state, functions, etc.), making it versatile for handling various scenarios, such as managing both data and loading states.
- Built-in Hook Support: Custom hooks can use built-in React hooks (useState, useEffect, useContext, etc.) to manage state, lifecycle, and context, allowing them to integrate seamlessly into React components.
- Maintainable and Modular Code: By extracting logic into custom hooks, your code becomes more maintainable and modular. Each custom hook represents a small piece of functionality, improving readability and testability.
- Avoids Repetitive Code: Custom hooks help reduce the need to write repetitive code in multiple components. For instance, handling form input logic can be abstracted into a custom hook.
- Can Be Composed with Other Hooks: Custom hooks can be composed together to build complex functionality. This allows for a flexible and clean way to combine hooks for more sophisticated use cases.
Performance Considerations
- Optimize API calls: For preventing the redundant requests caching mechanisms are used.
- Minimize state updates: Reduce unnecessary state changes inside custom hooks to improve efficiency.
- Use dependencies properly: Ensure hooks like useEffect have correct dependencies to prevent infinite loops.
Similar Reads
React Tutorial React is a powerful JavaScript library for building fast, scalable front-end applications. Created by Facebook, it's known for its component-based structure, single-page applications (SPAs), and virtual DOM,enabling efficient UI updates and a seamless user experience.Note: The latest stable version
7 min read
React Fundamentals
React IntroductionReactJS is a component-based JavaScript library used to build dynamic and interactive user interfaces. It simplifies the creation of single-page applications (SPAs) with a focus on performance and maintainability.React.jsWhy Use React?Before React, web development faced issues like slow DOM updates
8 min read
React Environment SetupTo run any React application, we need to first setup a ReactJS Development Environment. In this article, we will show you a step-by-step guide to installing and configuring a working React development environment.Pre-requisite:We must have Nodejs installed on our PC. So, the very first step will be
3 min read
React JS ReactDOMReactDom is a core react package that provides methods to interact with the Document Object Model or DOM. This package allows developers to access and modify the DOM. Let's see in brief what is the need to have the package. Table of ContentWhat is ReactDOM ?How to use ReactDOM ?Why ReactDOM is used
3 min read
React JSXJSX stands for JavaScript XML, and it is a special syntax used in React to simplify building user interfaces. JSX allows you to write HTML-like code directly inside JavaScript, enabling you to create UI components more efficiently. Although JSX looks like regular HTML, itâs actually a syntax extensi
6 min read
ReactJS Rendering ElementsIn this article we will learn about rendering elements in ReactJS, updating the rendered elements and will also discuss about how efficiently the elements are rendered.What are React Elements?React elements are the smallest building blocks of a React application. They are different from DOM elements
3 min read
React ListsReact Lists are used to display a collection of similar data items like an array of objects and menu items. It allows us to dynamically render the array elements and display repetitive data.Rendering List in ReactTo render a list in React, we will use the JavaScript array map() function. We will ite
5 min read
React FormsForms are an essential part of any application used for collecting user data, processing payments, or handling authentication. React Forms are the components used to collect and manage the user inputs. These components include the input elements like text field, check box, date input, dropdowns etc.
5 min read
ReactJS KeysA key serves as a unique identifier in React, helping to track which items in a list have changed, been updated, or removed. It is particularly useful when dynamically creating components or when users modify the list. In this article, we'll explore ReactJS keys, understand their importance, how the
5 min read
Components in React
React ComponentsIn React, React components are independent, reusable building blocks in a React application that define what gets displayed on the UI. They accept inputs called props and return React elements describing the UI.In this article, we will explore the basics of React components, props, state, and render
4 min read
ReactJS Functional ComponentsIn ReactJS, functional components are a core part of building user interfaces. They are simple, lightweight, and powerful tools for rendering UI and handling logic. Functional components can accept props as input and return JSX that describes what the component should render.What are Reactjs Functio
5 min read
React Class ComponentsClass components are ES6 classes that extend React.Component. They allow state management and lifecycle methods for complex UI logic.Used for stateful components before Hooks.Support lifecycle methods for mounting, updating, and unmounting.The render() method in React class components returns JSX el
4 min read
ReactJS Pure ComponentsReactJS Pure Components are similar to regular class components but with a key optimization. They skip re-renders when the props and state remain the same. While class components are still supported in React, it's generally recommended to use functional components with hooks in new code for better p
4 min read
ReactJS Container and Presentational Pattern in ComponentsIn this article we will categorise the react components in two types depending on the pattern in which they are written in application and will learn briefly about these two categories. We will also discuss about alternatives to this pattern. Presentational and Container ComponentsThe type of compon
2 min read
ReactJS PropTypesIn ReactJS PropTypes are the property that is mainly shared between the parent components to the child components. It is used to solve the type validation problem. Since in the latest version of the React 19, PropeTypes has been removed. What is ReactJS PropTypes?PropTypes is a tool in React that he
5 min read
React Lifecycle In React, the lifecycle refers to the various stages a component goes through. These stages allow developers to run specific code at key moments, such as when the component is created, updated, or removed. By understanding the React lifecycle, you can better manage resources, side effects, and perfo
7 min read
React Hooks
Routing in React
Advanced React Concepts
React Projects