React useDebounce Hook

ReactReactBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

In this lab, we will learn how to create a custom React hook called useDebounce that helps debounce user input. Debouncing is a technique that delays the invocation of a function until a certain amount of time has passed since the last time it was called. This technique is commonly used in scenarios where the user input triggers frequent updates to the application state, as it can help reduce unnecessary re-renders and improve performance.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL react(("`React`")) -.-> react/FundamentalsGroup(["`Fundamentals`"]) react(("`React`")) -.-> react/AdvancedConceptsGroup(["`Advanced Concepts`"]) react(("`React`")) -.-> react/StateManagementGroup(["`State Management`"]) react/FundamentalsGroup -.-> react/jsx("`JSX`") react/FundamentalsGroup -.-> react/event_handling("`Handling Events`") react/AdvancedConceptsGroup -.-> react/hooks("`React Hooks`") react/StateManagementGroup -.-> react/use_state_reducer("`Using useState and useReducer`") subgraph Lab Skills react/jsx -.-> lab-38378{{"`React useDebounce Hook`"}} react/event_handling -.-> lab-38378{{"`React useDebounce Hook`"}} react/hooks -.-> lab-38378{{"`React useDebounce Hook`"}} react/use_state_reducer -.-> lab-38378{{"`React useDebounce Hook`"}} end

React useDebounce Hook

index.html and script.js have already been provided in the VM. In general, you only need to add code to script.js and style.css.

To debounce a given value, you can create a custom hook that takes a value and a delay. Use the useState() hook to store the debounced value, and the useEffect() hook to update the debounced value every time value is updated. To delay invoking the setter of the previous state variable by delay ms, use setTimeout(). To clean up when dismounting the component, use clearTimeout(). This is particularly useful when dealing with user input.

Here is an example implementation of the useDebounce() hook:

const useDebounce = (value, delay) => {
  const [debouncedValue, setDebouncedValue] = React.useState(value);

  React.useEffect(() => {
    const handler = setTimeout(() => {
      setDebouncedValue(value);
    }, delay);

    return () => {
      clearTimeout(handler);
    };
  }, [value, delay]);

  return debouncedValue;
};

You can use the useDebounce() hook in a component like this:

const Counter = () => {
  const [value, setValue] = React.useState(0);
  const lastValue = useDebounce(value, 500);

  return (
    <div>
      <p>
        Current: {value} - Debounced: {lastValue}
      </p>
      <button onClick={() => setValue(value + 1)}>Increment</button>
    </div>
  );
};

ReactDOM.createRoot(document.getElementById("root")).render(<Counter />);

Please click on 'Go Live' in the bottom right corner to run the web service on port 8080. Then, you can refresh the Web 8080 Tab to preview the web page.

Summary

Congratulations! You have completed the React useDebounce Hook lab. You can practice more labs in LabEx to improve your skills.

Other React Tutorials you may like