Search code examples
reactjsreact-hooksrxjsobservablereact-custom-hooks

Observables-hooks How to to subscribe only on click


I am an angular dev who is new to React. I use observables to manage all my states as that is what I am familiar with. I am trying to figure out the best way to write a custom observable hook that only subscribes when the user clicks a button

I am trying to implement something like this:

const addMovieHandler = useCallback((movie) => {
setIsLoading(true);
addMovie$(movie).subscribe((data) => {
  console.log(data);
  fetchMovies()
});
 }, [fetchMovies]);

It works but it seems hacky and I do not know where to put the unsubscribe


Solution

  • You can make use of Subject as event emitter and subscribe to it in useEffect() - something like componentDidMount and unsubscribe() upon unmount to avoid memory leak. useRef() should be used so there is always one subject instance across the entire component lifecycle

    const onAddMovie=useRef(new Subject).current
    
    // Similar to angular OnNgInit 
    useEffect(()=>{
       const sub=>onAddMovie.pipe(
         switchMap(()=>fetchMovies())
         tap(()=>... side effect like setState)
       ).subscribe()
       return ()=>sub.unsubscribe()
    
    },[])
    
    <Button click={()=>onAddMovie.next()}> add movie </Button>