Cleanup usage in useEffect in React need or not need?



In the below usage for the useEffect hook, I am detecting the window width, then if the window is a certain width the function sets the state, but would I need to cleanup the useEffect in this case or would it need no cleanup? I know in the context of an API you could unsubscribe to the API in the return, So the return will run when the component un mounts

Is it correct in setting the windowWidth again or is it better to remove the return from the useEffect hook totally?

const [windowWidth, setWindowWidth] = React.useState<number>(0);
const [column, setColumn] = React.useState<number>(10);

const calcWindow = React.useCallback(() => {
  if (windowWidth < 768) {
    setColumn(() => 5);
  } else {
    setColumn(() => 10);
}, [windowWidth]);

React.useEffect(() => {
  return () => {
    setWindowWidth(window.innerWidth); // is this needed or is this correct?
}, [calcWindow, windowWidth]);


The returned function here is unnecessary. When the component is about
to unmount, you shouldn’t be setting the state since that state is just going to go away. During a re-render, the cleanup function will run and set window width, but the value will be overridden in the effect immediately from the setWindowWidth(window.innerWidth); call.

Answered By – Hanchen Jiang

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave A Reply

Your email address will not be published.

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More