when using react useEffect my app is crashing

Viewed 2016

i m changing a class component to a functional component and i m using hooks and useEffect so my app becoms really slow and crushs without any error

import React, { useState, useEffect } from 'react';
import Toolbar from '@material-ui/core/Toolbar';

const FancyToolBar = ({ children }) => {
  const [backGround, togglebackGround] = useState('white');
  const listenScrollEvent = () => {
    if (window.scrollY > 80) {
      togglebackGround('black');
    } else {
      togglebackGround('white');
    }
  };
  useEffect(() => {
    window.addEventListener('scroll', listenScrollEvent);
  });
  const logo = backGround === 'white'
    ? <img src="/images/1.jpg" alt="" style={{ width: '50px !important', height: '50px' }} />
    : <img src="/images/2.png" alt="" style={{ width: '50px !important', height: '50px' }} />;
  return (
    <Toolbar style={{ backgroundColor: backGround }}>
      {logo}
      {children}
    </Toolbar>
  );
};


export default FancyToolBar;
1 Answers

There are two things that you need to address.

First: you need to cleanup your eventListener.

Second: only add the event listener on initial mount by adding [] as the second parameter to useEffect

useEffect(() => {
    window.addEventListener('scroll', listenScrollEvent);
    return () => {
      window.removeEventListener('scroll', listenScrollEvent);
    }
  }, []);
Related