0

I'm using the code from React conditionally render based on viewport size but i don't understand one thing: i added a console log inside the useEffect and when i add the brackets [ ] at final as you can see bellow. This makes the useeffect only run once and seems it works because the console log only show once when i refresh the page. But when i use React Developer Tools on the browser, the state windowsSize is keeping updating the value according to what I update the window size.

const Navbar = () => {
const [windowSize, setwindowSize] = useState(window.innerWidth);
const updateWindowsSize = () => {
    setwindowSize(window.innerWidth)
}
useEffect(() => {
    console.log(windowSize)
    window.addEventListener("resize", updateWindowsSize);

    return () => window.removeEventListener("resize", updateWindowsSize);
  },[]);

return (
<Fragment>
    {windowSize>1000 ? (<NavDesk/>) : (<NavSmartPhone/>)} 
</Fragment>
);}

1 Answers1

0

The only purpose of useEffect is that it adds the listener when the component mounts and removes it when the component unmounts

State is updating constantly because you have added an EventListener to the DOM which which will constantly listen for the event which is "resize" here and as long as the event is being fired it will update the callback function,

royalbhati
  • 296
  • 3
  • 10