Creating A Custom Hook In React

Hello, everyone! I’m excited to embark on a journey of sharing some valuable custom hooks for React projects. Custom hooks are powerful tools in the world of React development, and I’ve decided to create a collection of these hooks. What’s more, once we’ve built a substantial collection, I plan to convert them into a package for easy integration and reuse. So, join me as we explore the world of React Custom Hooks and enhance our React development projects!

First of the custom hooks we’ll explore is the useDebounce hook, which is extremely useful for handling media queries in your React applications. Let’s dive into the code and see how you can create and use this custom hook to make your applications responsive.

hooks/useDebounce.tsx:

import { useEffect, useState } from 'react';

const useDebounce = (initialValue: T, timeOutInMs = 500): T => {
  const [value, setValue] = useState(initialValue);

  useEffect(() => {
    const timer = setTimeout(() => {
      setValue(initialValue);
    }, timeOutInMs);

    // Clear the timer if the effect re-runs before the timeout
    return () => {
      clearTimeout(timer);
    };
  }, [initialValue, timeOutInMs]);

  return value;
};
export default useDebounce;
export { useDebounce };

Code language: TypeScript (typescript)

Usage example:

import React,{ useState, useEffect, useCallback } from 'react';
import useDebounce from './useDebounce'; // Import your custom hook

function SearchComponent() {
  const [searchTerm, setSearchTerm] = useState('');
  const debouncedSearchTerm = useDebounce(searchTerm, 500);

  const handleSearch = useCallback((query) => {
    // Perform your search or API call using debouncedSearchTerm
    // For example, fetch search results from an API
    fetch(`https://api.example.com/search?query=${query}`)
      .then((response) => response.json())
      .then((data) => {
        // Handle and display search results
        console.log(data);
      })
      .catch((error) => {
        console.error(error);
      });
  }, []);

  useEffect(() => {
    handleSearch(debouncedSearchTerm);
  }, [debouncedSearchTerm]);

  return (
    <div>
      <input
        type="text"
        placeholder="Search..."
        value={searchTerm}
        onChange={(e) => setSearchTerm(e.target.value)}
      />
    </div>
  );
}

export default SearchComponent;Code language: TypeScript (typescript)

Explanation:

  1. Import the “useDebounce” custom hook.
  2. In the SearchComponent, maintain the searchTerm state to capture input, and use “useDebounce” with a 500ms delay for debouncedSearchTerm.
  3. Use useCallback to memoize the handleSearch function, optimizing performance by preventing unnecessary recreations during re-renders.
  4. Utilize useEffect to call the memoized handleSearch function when debouncedSearchTerm changes. This ensures API requests are made after the user finishes typing, enhancing the user experience and performance.

This code efficiently handles debounced search terms, and useCallback optimizes handleSearch for performance, making it a solid foundation for your React search functionality.

Conclusion

In this article, we’ve explored the power of the “useDebounce” custom hook. This tool is invaluable for handling input events and optimizing performance, ensuring a smoother user experience.

Our journey in the world of React Custom Hooks is just beginning, and I’m excited to create and share more of these hooks. I plan to transform them into a package for easy integration and reuse, contributing to the React community and powerful, reusable solutions.

Thank you for joining me on this journey, and I look forward to sharing more insights and tools to empower your React development projects.

Leave a Reply

Your email address will not be published. Required fields are marked *