Answer the question
In order to leave comments, you need to log in
How to properly use useEffect?
Hello.
The application consists of a single component that shows the current page dimensions.
If I do this, I immediately get into a loop:
let PageSize = ( ) => {
const [webPageSize, setWebPageSize] = useState(
[document.documentElement.scrollWidth,
document.documentElement.scrollHeight]
)
useEffect( ( ) => {
setWebPageSize(
[document.documentElement.scrollWidth,
document.documentElement.scrollHeight]
)
} , /* здесь надо передать второй аргумент, но не понимаю какой. на webPageSize ругается */ )
return (
<h1>{`webPageSize width is ${webPageSize[0]}. webPageSize height is ${webPageSize[1]}`}</h1>
)
}
let PageSize = ( ) => {
const [webPageSize, setWebPageSize] = useState(
[document.documentElement.scrollWidth,
document.documentElement.scrollHeight]
)
function handleWindowResize() {
setWebPageSize(
[document.documentElement.scrollWidth,
document.documentElement.scrollHeight]
)
}
window.addEventListener( "resize", handleWindowResize, false)
useEffect( ( ) => {
return ( ) => window.removeEventListener("resize", handleWindowResize, false)
})
return (
<h1>{`webPageSize width is ${webPageSize[0]}. webPageSize height is ${webPageSize[1]}`}</h1>
)
}
Answer the question
In order to leave comments, you need to log in
The second option is almost correct.
1. Add an event inside useEffect
;
2. You deps
are passing an empty array;
3. In rendering, you can write easier without using a template string.
const PageSize = () => {
const [pageSize, setPageSize] = useState([document.documentElement.scrollWidth, document.documentElement.scrollHeight]);
const updatePageSize = () => setPageSize([document.documentElement.scrollWidth, document.documentElement.scrollHeight]);
useEffect(() => {
window.addEventListener('resize', updatePageSize);
return () => {
window.removeEventListener('resize', updatePageSize);
};
}, []);
return (
<div>
<p>page width is {pageSize[0]}</p>
<p>page height is {pageSize[1]}</p>
</div>
);
};
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question