≡ Menu

Credit:http://bit.ly/3FWT3Or

Have you ever noticed how some search bars feel incredibly smooth, only firing off a search query once you’ve stopped typing for a moment?

Or perhaps you’ve built an app where an action triggers too frequently, leading to performance issues.

If so, you’ve encountered the need for debouncing.

In React, we can easily implement this powerful technique using a custom hook called useDebounce.

It’s a game-changer for optimizing performance and enhancing user experience.

Let’s dive in and see how it works!

What is Debouncing and Why Do We Need It?

Debouncing is a programming pattern that limits the rate at which a function can fire.

When you’re typing into a search box, for instance, each keystroke updates the input’s value.

Without debouncing, an API call for search results might be triggered with every single character you type.

Imagine searching for “React Hooks Tutorial”:

  • R -> search for “R”
  • Re -> search for “Re”
  • Rea -> search for “Rea”
  • …and so on.

This creates a flurry of unnecessary requests to your server, wasting resources and potentially slowing down your application.

Debouncing solves this by introducing a delay. It waits for a specified period of inactivity before executing the function. If the “activity” (like typing) continues within that delay, the timer resets. The function only runs after the activity stops for the set duration.


Building Our useDebounce Hook

Let’s break down the useDebounce hook. We’ll create a file named useDebounce.js for this.

import { useState, useEffect } from 'react';

function useDebounce(value, delay) {
  // State to store the debounced value
  const [debouncedValue, setDebouncedValue] = useState(value);

  useEffect(() => {
    // Set a timeout to update the debounced value after the specified delay
    const handler = setTimeout(() => {
      setDebouncedValue(value);
    }, delay);

    // Clean up the timeout if the value or delay changes, or if the component unmounts
    return () => {
      clearTimeout(handler);
    };
  }, [value, delay]); // Only re-run if value or delay changes

  return debouncedValue;
}

export default useDebounce;

Let’s dissect what’s happening here:

  • useState(value): We initialize a state variable debouncedValue with the initial value that’s passed into our hook. This debouncedValue is what our component will actually “see” after the delay.
  • useEffect(() => { ... }, [value, delay]): This is where the magic happens.
    • The useEffect hook runs whenever value or delay changes.
    • setTimeout(...): Inside the effect, we set a timer. After the specified delay, the setDebouncedValue(value) function is called, updating our debouncedValue state to the current value.
    • Cleanup Function (return () => { clearTimeout(handler); }): This part is crucial for proper debouncing. If value changes before the setTimeout finishes (i.e., the user types another character), this cleanup function runs. It clears the previous setTimeout, effectively resetting the timer. This ensures that the setDebouncedValue only happens once the user has stopped typing for the entire delay duration.

Putting useDebounce into Practice: A Search Input Example

Now that we have our useDebounce hook, let’s see how to use it in a typical search input component.

import React, { useState, useEffect } from 'react'; // Don't forget useEffect here!
import useDebounce from './useDebounce'; // Assuming you save the hook in useDebounce.js

function SearchInput() {
  const [searchTerm, setSearchTerm] = useState('');
  const debouncedSearchTerm = useDebounce(searchTerm, 500); // Debounce by 500ms

  // This effect will only run after 500ms of no typing
  useEffect(() => {
    if (debouncedSearchTerm) {
      console.log('Fetching data for:', debouncedSearchTerm);
      // In a real app, you'd make an API call here, e.g.,
      // fetchData(debouncedSearchTerm);
    } else {
      console.log('Search term cleared.');
    }
  }, [debouncedSearchTerm]); // Trigger this effect only when debouncedSearchTerm changes

  const handleChange = (event) => {
    setSearchTerm(event.target.value);
  };

  return (
    <div>
      <input
        type="text"
        placeholder="Search..."
        value={searchTerm}
        onChange={handleChange}
      />
      <p>Current search term: {searchTerm}</p>
      <p>Debounced search term (used for fetching): {debouncedSearchTerm}</p>
    </div>
  );
}

export default SearchInput;

In this SearchInput component:

  1. We maintain the searchTerm state, which updates immediately with every keystroke.
  2. We pass searchTerm and a delay of 500 milliseconds to our useDebounce hook. The hook returns debouncedSearchTerm.
  3. A separate useEffect monitors debouncedSearchTerm. This useEffect will only run when debouncedSearchTerm actually changes, which happens after the user has paused typing for 500ms.
  4. Inside this useEffect, you’d typically trigger your data fetching logic (e.g., an API call) using the stable debouncedSearchTerm.

You can try this out yourself! As you type quickly, notice how the “Debounced search term” paragraph (and the console log) only updates after you stop typing for half a second.


Beyond Search Inputs

The useDebounce hook isn’t just for search bars! You can use it for:

  • Resizing windows: Only update layout calculations after the user has finished resizing.
  • Form validations: Validate input only after the user pauses typing, rather than on every keystroke.
  • Autosave features: Save user progress only after a period of inactivity.
  • Any scenario where you want to limit the frequency of an action based on continuous user input.

Conclusion

The useDebounce custom hook is a simple yet incredibly powerful tool for optimizing your React applications.

By intelligently delaying actions based on user input, you can significantly improve performance, reduce unnecessary requests, and provide a smoother, more responsive user experience.

Incorporate debouncing into your React toolkit, and your users will thank you!

Do you have any other common performance bottlenecks in your React apps that you’re looking to solve?

If so let us know in the comments section below!

{ 0 comments }

5 Tips That Will Make You a Better Programmer

If you want to have more success as a coder,be able to get more done in less time and simply be more effective then these tips will help!

Tip # 1 – Learn from the best. If you want to be the best you need to learn from the best!

There is a reason the cost of an education from an ivy league college is way more than say your local community college.

When you go to an ivy league college you are getting the best education that money can buy and you are being taught by some of the best teachers and instructors in the world.

Two guys on YouTube that really know their stuff when it comes to software engineering and building applications is Tech with Tim and Bro Code.

Tip # 2 – Build projects. Great programmers build real world projects that are useful and solve a problem.

If you are a novice programmer start out small and build a small project like a to-do app,weather app or a simple game of tic-tac-toe.

Once you level up your skills as a programmer then start building larger full stack applications.

Tip # 3 – Sharpen up your programming skills.

Abraham Lincoln said if he had six hours to chop down a tree he would spend the first four sharpening his axe!

A few ways to sharpen up your programming skills is to solve Leet Code problems,brush up on the fundamentals and learn a new in-demand web framework or programming language.

Practice coding for at least one hour a day. Consistency is key!

Tip # 4 – Teach. One of the best ways to have a deep level of understanding of a topic is to teach it.

Become a creator (start a YouTube channel or blog) and start teaching some of the programming topics you are learning.

Tip # 5 – Hire a coach. If you feel stuck and are struggling to get to the next level in your career it might be time to get a coach.

A coach can see the blind spots and will be able to see where there are areas for improvement.

If you work for a company you might not even need a coach because you can learn from engineers and programming managers that are smarter and have more experience than you.

Put these 5 tips into action and you can’t help but be a better programmer in your business or at your job.

What has helped you become a better software engineer? Let us know in the comments section below!

Check out some awesome offers below:

Get Bluehost hosting for as little as $1.99/month (save 75%)…https://bit.ly/3C1fZd2

Let me and my team build you a money making website or blog…https://bit.ly/tnrwebsite_service

Join my Patreon for one-on-one coaching and help with your coding…https://www.patreon.com/c/TyronneRatcliff

Buy me a coffee ☕️https://buymeacoffee.com/tyronneratcliff

 

 

 

 

 

 

{ 0 comments }