I\'m trying to dive deeper into rxjs and found an issue where the input field I\'m trying to debounce dispatches an event on every keypress, the debounce only holds the outp
React continuously calls your function to render the component. Therefore the Subject is continuously recreated.
Using a factory with useState to keep the subject and working with useEffect to make sure the subscription is only made once should fix your issue.
Something like this :
import React, { Component, useState, useEffect, useRef } from 'react';
import { render } from 'react-dom';
import { debounceTime, map, tap, distinctUntilChanged } from 'rxjs/operators';
import { fromEvent, Subject } from 'rxjs';
import './style.css';
const App = props => {
const [queryName, setQueryName] = useState("");
const [debouncedName, setDebouncedName] = useState("");
const [onSearch$] = useState(()=>new Subject());
useEffect(() => {
const subscription = onSearch$.pipe(
debounceTime(400),
distinctUntilChanged(),
tap(a => console.log(a))
).subscribe(setDebouncedName);
}, [])
const handleSearch = e => {
setQueryName(e.target.value);
onSearch$.next(e.target.value);
};
return (
Debounced: {debouncedName}
);
}
render( , document.getElementById('root'));