I have created a function which is listening for the resize event it checks for the window width and updates my IsMobile variable if(width<=600 and IsMobile = false) then set it to true and vice versa.
here is the code:
import React, { useEffect, useState } from 'react';
export interface MechnicalLiftProps {
}
const MechnicalLift: React.SFC<MechnicalLiftProps> = () => {
const [IsMobile, setIsMobile] = useState(true)
const handleWindowChange = () => {
console.log('window inner width', window.innerWidth);
console.log('is mobile in handle', IsMobile);
if (window.innerWidth <= 600 && IsMobile === false) {
setIsMobile(true);
console.log('is mobile set to true');
}
if (window.innerWidth > 600 && IsMobile === true) {
setIsMobile(false);
console.log('is mobile set to false');
}
}
useEffect(() => {
console.log('mount running');
window.addEventListener('resize', handleWindowChange)
handleWindowChange()
return () => {
window.removeEventListener('resize', handleWindowChange)
}
}, [])
useEffect(() => {
console.log('is this mobile ', IsMobile);
}, [IsMobile])
return (
<div>
</div>
);
}
export default MechnicalLift;
my console output:
i feel initial state is being set every time the component is re rendered otherwise why is IsMobile set to true every time in handle window change even though its set multiple times to false. new to hooks please elaborate your explanation as much as possible
