Search code examples
javascriptreactjslodashdebouncing

Implementing Lodash's debounce in a ReactJS functional component


I'm trying to debounce text input field change with Lodash's debounce function.

import React from "react";
import debounce from 'lodash.debounce';

const Input = () => {

  const onChange = debounce((e) => {
    const { value } = e.target;
    console.log('debounced value', value)
  }, 1000)

  return (

    <input type="text" onChange={ onChange } />

  )
};

The code above throws the following errors:

Warning: This synthetic event is reused for performance reasons. If you're seeing this, you're accessing the property target on a released/nullified synthetic event. This is set to null. If you must keep the original synthetic event around, use event.persist().

Uncaught TypeError: Cannot read property 'value' of null

What is the correct implementation?


Solution

  • When to Use Refs There are a few good use cases for refs:

    • Managing focus, text selection, or media playback.
    • Triggering imperative animations.
    • Integrating with third-party DOM libraries.

    Avoid using refs for anything that can be done declaratively.

    Refs and the DOM

    The way you defined Input, I am assuming it would be used in many places. So, I would do this:

    import React from "react";
    import debounce from 'lodash.debounce';
    
    const Input = () => {
    
      // Debounced function
      // `printValue` only cares about last state of target.value
      const printValue = debounce(value => console.log(value), 1000);
    
      // Event listener called on every change
      const onChange = ({ target }) => printValue(target.value);
    
      return <input type="text" onChange={ onChange } />;    
    
    };