Debounce inside functional component in React.js

Viewed 1919

Trying to create a delay on react component that has input field that updates on change.

Here's the code:

import React from 'react'; 
import Input from "@material-ui/core/Input";
import {debounce} from "lodash";
...

const SampleRow = () => {
    let [newFriend, setNewFriend] = React.useState({name: '', lastSeen: '', contactIn: ''});

    const onAddFriend = debounce(() => {
        if(newFriend.name.length === 0){
            return;
        }
        console.log(newFriend.name);
    }, 2000);

    return (
        <TableRow>
            <TableCell component="th" scope="row">
                <Input
                    value={newFriend.name}
                    onChange={(event) => {
                        setNewFriend({...newFriend, name: event.target.value});
                        onAddFriend();
                    }}
                    placeholder={"Add friend"}
                    disableUnderline={true}
                />
            </TableCell>
            <TableCell align="left">{newFriend.lastSeen ? newFriend.lastSeen : ''}</TableCell>
            <TableCell align="left">{newFriend.contactIn ? newFriend.contactIn : ''}</TableCell>
            <TableCell align="left" className={classes.externalLinks}/>
        </TableRow>
    )
};

What happens is that the console.log prints out every change (after the timeout of 2s), and won't cancel the previous triggers.

The question is why is that happens? and how could this could be solved?

I've found similar questions with complex useDebounce logic or class-components. Didn't find a reference for this problem.

3 Answers

The issue here is that your debounced function is being recreated on each render.

One way to solve this is to move it out of the functional component. Another way is to change your component to a Class component and save your debounced function as a property.

const { useState } = React
const { debounce } = _;

const onAddFriend = debounce(console.log, 2000);

const App = () => {
 
  const [newFriend, setNewFriend] = useState({name: '',   lastSeen: '', contactIn: ''});
  
  const handleInput = (event) => {
    setNewFriend({...newFriend, name: event.target.value});
    onAddFriend(event.target.value);
  }
  
  return (
    <div className="box">
      <form className="form">
        <div class="field">
          <label for="name-1">Update  {newFriend.name}</label>
          <div class="control">
            <input type="text" name="name-1" value={newFriend.name}
                    onChange={handleInput} class="input"/>
          </div>
        </div>
      </form>
    </div>
  )
}

ReactDOM.render(<App />,
document.getElementById("root"))
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.19/lodash.min.js"></script>
<script src="https://unpkg.com/react@16.7.0-alpha.0/umd/react.production.min.js"></script>
<script src="https://unpkg.com/react-dom@16.7.0-alpha.0/umd/react-dom.production.min.js"></script>

<div id="root"></div>

Ciao, try to cancel the prevoius trigger:

import React from 'react'; 
import Input from "@material-ui/core/Input";
import {debounce} from "lodash";
...

const SampleRow = () => {
  let [newFriend, setNewFriend] = React.useState({name: '', lastSeen: '', contactIn: 
''});

const onAddFriend = debounce((abort) => {
    if(abort){
        return;
    }
    console.log(newFriend.name);
}, 2000);

return (
    <TableRow>
        <TableCell component="th" scope="row">
            <Input
                value={newFriend.name}
                onChange={(event) => {
                    setNewFriend({...newFriend, name: event.target.value});
                    let abort = false;
                    if(event.target.value.length === 0){
                      abort = true;
                    }
                    onAddFriend(abort);
                }}
                placeholder={"Add friend"}
                disableUnderline={true}
            />
        </TableCell>
        <TableCell align="left">{newFriend.lastSeen ? newFriend.lastSeen : ''}</TableCell>
        <TableCell align="left">{newFriend.contactIn ? newFriend.contactIn : ''}</TableCell>
        <TableCell align="left" className={classes.externalLinks}/>
    </TableRow>
)
  };
Related