Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

146
Views
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(() => {
  setWindowWidth(window.innerWidth);
  calcWindow();
  return () => {
    setWindowWidth(window.innerWidth); // is this needed or is this correct?
  };
}, [calcWindow, windowWidth]);
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!