Add and remove scroll event for window in the React App

Add scroll event for window in React App

With Class component:

componentDidMount() {
    window.addEventListener('scroll', this.handleScroll, true);
},

componentWillUnmount() {
    window.removeEventListener('scroll', this.handleScroll, true);
},

handleScroll = event => {
 // handle scroll
},


Function component:

  const handleScroll = event => {
   // handle scroll
  };
  
  useEffect(() => {
    window.addEventListener('scroll', handleScroll, true);
    return () => {
      window.removeEventListener('scroll', handleScroll, true);
    };
  }, []);


Add return method at the end of useEffect to clean or remove event that you have added after un-mouted a component


© 2019 4codev

Created with love by Sil.