codingstuff.io
ExploreTutorialsProblemsCS Subjects
Get Started
ExploreTutorialsProblemsCS Subjects
Get Started
codingstuff.io

Master the art of building software through interactive tutorials, real-world problems, and guided projects.

Pune, Maharashtra, India

codingstuffmail@gmail.com

Product

  • Explore
  • Tutorials
  • Problems
  • CS Subjects

Company

  • About
  • Contact
  • Privacy Policy
  • Terms & Conditions
  • Sitemap

© 2026 codingstuff.io. All rights reserved.

Built with ❤️ for developers everywhere

/
/
All Tutorials
⚛️

React.js

22 / 61 topics
18Context API Basics19Hooks: Introduction and Overview20Using the useState Hook21Using the useEffect Hook22Creating Custom Hooks23Memoization in React
Tutorials/React.js/Creating Custom Hooks
⚛️React.js

Creating Custom Hooks

Updated 2026-04-20
3 min read

Introduction

In React, hooks are functions that let you "hook into" React state and lifecycle features from function components. Custom hooks are a powerful feature that allows you to extract component logic into reusable functions. This tutorial will walk you through the process of creating custom hooks in React.js, providing real-world examples and best practices.

What is a Custom Hook?

A custom hook is a JavaScript function whose name starts with use and that may call other hooks. The purpose of a custom hook is to encapsulate and reuse logic across different components. By using custom hooks, you can write more readable and maintainable code.

Benefits of Using Custom Hooks

  1. Code Reusability: Extract common logic into reusable functions.
  2. Improved Readability: Simplify complex components by breaking them down into smaller, manageable pieces.
  3. Encapsulation: Keep related stateful logic together.
  4. Testing: Easier to test individual hooks in isolation.

Creating a Custom Hook

Let's start by creating a simple custom hook that manages form input state and validation.

Example: useFormInput

import { useState } from 'react';

function useFormInput(initialValue) {
  const [value, setValue] = useState(initialValue);

  function handleChange(e) {
    setValue(e.target.value);
  }

  return {
    value,
    onChange: handleChange,
  };
}

Explanation

  1. State Initialization: We use the useState hook to initialize the input's state with the provided initialValue.
  2. Change Handler: The handleChange function updates the state whenever the input changes.
  3. Return Object: The custom hook returns an object containing the current value and the change handler.

Usage

import React from 'react';
import useFormInput from './useFormInput';

function SignupForm() {
  const email = useFormInput('');
  const password = useFormInput('');

  function handleSubmit(e) {
    e.preventDefault();
    console.log('Email:', email.value);
    console.log('Password:', password.value);
  }

  return (
    <form onSubmit={handleSubmit}>
      <div>
        <label>Email:</label>
        <input type="email" {...email} />
      </div>
      <div>
        <label>Password:</label>
        <input type="password" {...password} />
      </div>
      <button type="submit">Sign Up</button>
    </form>
  );
}

export default SignupForm;

Explanation

  1. Import Custom Hook: We import the useFormInput custom hook.
  2. Initialize Inputs: We use the custom hook to manage the state of the email and password inputs.
  3. Form Submission: The form submission handler logs the input values to the console.

Advanced Example: useFetch

Let's create a more advanced custom hook that fetches data from an API.

Example: useFetch

import { useState, useEffect } from 'react';

function useFetch(url) {
  const [data, setData] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    async function fetchData() {
      try {
        const response = await fetch(url);
        if (!response.ok) {
          throw new Error('Network response was not ok');
        }
        const json = await response.json();
        setData(json);
      } catch (err) {
        setError(err.message);
      } finally {
        setLoading(false);
      }
    }

    fetchData();
  }, [url]);

  return { data, loading, error };
}

Explanation

  1. State Initialization: We use useState to manage the fetched data, loading status, and any errors.
  2. Data Fetching: The useEffect hook is used to fetch data from the provided URL when the component mounts or the URL changes.
  3. Error Handling: Errors are caught and stored in the state.
  4. Return Object: The custom hook returns an object containing the fetched data, loading status, and any errors.

Usage

import React from 'react';
import useFetch from './useFetch';

function UserList() {
  const { data: users, loading, error } = useFetch('https://api.example.com/users');

  if (loading) return <p>Loading...</p>;
  if (error) return <p>Error: {error}</p>;

  return (
    <ul>
      {users.map(user => (
        <li key={user.id}>{user.name}</li>
      ))}
    </ul>
  );
}

export default UserList;

Explanation

  1. Import Custom Hook: We import the useFetch custom hook.
  2. Data Fetching: We use the custom hook to fetch user data from an API.
  3. Conditional Rendering: Based on the loading status and any errors, we render appropriate UI elements.

Best Practices for Creating Custom Hooks

  1. Naming Conventions: Always start custom hooks with use to make them recognizable as hooks.
  2. Single Responsibility: Each hook should focus on a single responsibility.
  3. Avoid Side Effects in Render: Ensure that any side effects are handled within useEffect.
  4. Reusability: Design hooks to be reusable across different components.
  5. Documentation: Provide clear documentation for your custom hooks, including expected parameters and return values.

Conclusion

Custom hooks in React.js provide a powerful way to encapsulate and reuse logic across components. By following the best practices outlined in this tutorial, you can create maintainable and reusable custom hooks that enhance the readability and functionality of your React applications.


PreviousUsing the useEffect HookNext Memoization in React

Recommended Gear

Using the useEffect HookMemoization in React