how to detect window is loaded in react
Solution 1:
I solve same problem with this context api hook.
import React, { createContext, useContext, useEffect, useState } from 'react';
export const SizeContext = createContext();
const SizeContextProvider = ({ children }) => {
const [width, setWidth] = useState(window.innerWidth);
const [isMobile, setIsMobile] = useState(true);
const [isDesktop, setIsDesktop] = useState(true);
function debounce(fn, ms) {
let timer;
return () => {
clearTimeout(timer);
timer = setTimeout(() => {
timer = null;
fn.apply(this, arguments);
}, ms);
};
}
useEffect(() => {
const debouncedHandleResize = debounce(() => {
setWidth(window.innerWidth);
}, 0);
window.addEventListener('resize', debouncedHandleResize);
return () => {
window.removeEventListener('resize', debouncedHandleResize);
};
});
useEffect(() => {
if (width <= 575) {
setIsMobile(true);
setIsDesktop(false);
} else if (width >= 576 && width < 767) {
setIsMobile(true);
setIsDesktop(false);
} else if (width >= 768 && width < 991) {
setIsMobile(false);
setIsDesktop(true);
} else if (width >= 992 && width < 1199) {
setIsMobile(false);
setIsDesktop(true);
} else {
setIsMobile(false);
setIsDesktop(true);
}
}, [width]);
return (
<SizeContext.Provider value={{ width, isDesktop, isMobile }}>
{children}
</SizeContext.Provider>
);
};
export const useSizeContext = () => useContext(SizeContext);
export default SizeContextProvider;
import context api use any component.
const App = () => {
return (
<SizeContextProvider>
<Device />
</SizeContextProvider>
)
}
Here Device Component use Context Api
const Device = () => {
const { isMobile, isDesktop } = useSizeContext();
return (
<div>
{isMobile && <h1> Small Device </h1>}
{isDesktop && <h1> Largest Device </h1>}
</div>
);
}