'react how to stop useffect causing components to rerender
I have a useeffect hook which is causing a css animated component in my salesHeader component to re-render every time I scroll to the top of the page.
How can I stop this?
I only want to show and hide the showSignUp component when scrolled to the top of page, not cause other components to re-render.
const SalesScreen = () => {
const [showSignUp, setShowSignUp] = useState(false);
useEffect(() => {
window.addEventListener('scroll', onScroll, false);
return () => window.removeEventListener('scroll', onScroll, false);
}, []);
const onScroll = () => {
window.scrollY > 0 ? setShowSignUp(true) : setShowSignUp(false);
};
return (
<Layout noHeader noContainer noBottomMarginBanner>
<SalesHeader data={salesData} />
{showSignUp && <SalesSignUp />}
</Layout>
);
};
Solution 1:[1]
The rerender of your component is not caused by the useEffect, but by the setState that you attached to the scroll event. That's why everytime you scroll your component is re rendering.
The code below could help you to not re render multiple times, by calling setState when your scroll value is top :
const onScroll = () => {
if (window.scrollY > 0 && !showSignUp)
setShowSignUp(true);
else if (showSignUp)
setShowSignUp(false);
}
I hope it helped you
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | A.Vinuela |
