Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

when using react useEffect my app is crashing

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;
like image 466
edaly Ahmed Avatar asked Jan 02 '19 16:01

edaly Ahmed


People also ask

Does useEffect run before or after render?

Does useEffect run after every render? Yes! By default, it runs both after the first render and after every update.

Does useEffect cause re-render?

Inside, useEffect compares the two objects, and since they have a different reference, it once again fetches the users and sets the new user object to the state. The state updates then triggers a re-render in the component.

Can I use useMemo instead of useEffect?

The useMemo version immediately renders 1 . The useEffect version renders null , then after the component renders the effect runs, changes the state, and queues up a new render with 1 .

Does useEffect run on first render?

3.2 Component did update name prop is mentioned in the dependencies argument of useEffect(..., [name]) . useEffect() hook runs the side-effect after initial rendering, and on later renderings only if the name value changes.


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);
    }
  }, []);
like image 86
Shubham Khatri Avatar answered Nov 15 '22 09:11

Shubham Khatri