O
O
Ostic2021-03-06 16:55:46
React
Ostic, 2021-03-06 16:55:46

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>
  )
}

Question: is it possible to pass a second argument here so that there is no loop?

This is how it works without errors and does not swear:
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>
  )
}

but this solution looks crooked, in my opinion.
What is the right thing to do in such a situation?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander, 2021-03-06
@Ostic

The second option is almost correct.
1. Add an event inside useEffect;
2. You depsare 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 question

Ask a Question

731 491 924 answers to any question