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;
Does useEffect run after every render? Yes! By default, it runs both after the first render and after every update.
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.
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 .
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.
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);
}
}, []);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With