ReasonJun

React : debounce 본문

Frontend/React

React : debounce

ReasonJun 2023. 6. 14. 19:01
728x90

In React, "debounce" refers to a technique used to delay the execution of a function or action until a certain amount of time has passed without any subsequent calls. It helps optimize performance by reducing unnecessary or frequent function invocations, particularly in scenarios like user input handling or event listeners.

 

Debouncing is commonly used in React applications when you want to delay the execution of a function triggered by user input (e.g., typing in an input field) until the user has paused typing for a specific duration. This can prevent excessive or rapid updates that could potentially impact performance or overload server requests.

 

There are various ways to implement debouncing in React. Here's an example using the lodash library, which provides a debounce utility function:

import React, { useState } from 'react';
import { debounce } from 'lodash';

const MyComponent = () => {
  const [inputValue, setInputValue] = useState('');

  const handleInputChange = debounce(value => {
    // Perform some action with the debounced value
    console.log('Debounced value:', value);
  }, 500); // Set the debounce delay to 500 milliseconds

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

  return (
    <div>
      <input type="text" value={inputValue} onChange={handleChange} />
    </div>
  );
};

export default MyComponent;

without lodash (useEffect)

import { useEffect, useState } from 'react';

export const useDebounce = (value, delay) => {
  const [debounceValue, setDebounceValue] = useState(value);

  useEffect(() => {
    const handler = setTimeout(() => {
      setDebounceValue(value);
    }, delay);

// If the value is not maintained during the delay, it disappears with the specified setTimeout.
    return () => {
      clearTimeout(handler);
    };
  }, [value, delay]);

  return debounceValue;
};

This debounce mechanism helps reduce the number of function calls and ensures that the action is performed only when the user has finished typing, improving performance and responsiveness.

 

It's worth noting that there are other debounce implementations available, such as using setTimeout and clearTimeout directly or using custom debounce hooks. The approach may vary depending on your specific requirements and the libraries or utilities you choose to work with.

728x90
Comments