reactjsthrottlingdebouncingreact-final-formfinal-form

how to debounce a final-form Field?


this is a pretty common query, but I am a bit confused with the new final-form library. I used to work with redux-form but this new version is too different.

My need is simple, I want to dispatch a search as the user writes in some text, but I want to add a throttle to the Field.

Here is a first attempt with the lib react-final-form-listeners, but as you will see, when you write in the text field, the debounce does not work :/

https://codesandbox.io/embed/react-final-form-simple-example-khkof


Solution

  • First, I'd encourage you to do all of this without using an obscured package layer. This will help you truly understand the flow, but nevertheless, here's how you can call a function when the input changes:

    In this case, I just created a debounced function outside of the render method. This varies when using classes instead of hooks:

    Hooks:

    const handleSearch = debounce(searchText => { ... }, 500);
    

    Classes (or you can debounce the class field in the constructor, either work):

    class Example extends Component {
      handleSearch = debounce(searchText => { ... }, 500)
    
      render = () => { ... }
    }
    

    Working example (type while the codesandbox console is open):

    Edit 🏁 React Final Form - Simple Example


    The differences between debounced, throttled, and normal execution:

    enter image description here


    Same as above, minus react-final-form and react-final-form-listeners (two less dependencies in your project!):

    Working example (type while the codesandbox console is open):

    Edit Simple Form - Simple Example