Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Too Many Rerenders – Storing useLocation().state variable in a useState() variable

The URL contains an ID of a project. If a user navigated to the projects page from a projects overview page, the project info would already be stored in useLocation().state, however, if they access this hyperlink from outside, useLocation().state would be null.

I first declare coverImageUrl and setCoverImageURL state variables, set them to null, and then want to either manually fetch them if they haven’t been passed as parameters, or load them from useLocation().state.

Under current testing scenarios I’m dealing only with situations where these parameters are passed however, I am getting a too many re-renders error and I’m not sure why.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Code:

const state = useLocation().state
let project = null
const [coverImageURL, setCoverImageURL] = useState('')

if(!!state && 'project' in state && 'coverImageURL' in state) { // parameters passed
    project = state.project
    console.log(`parameters supplied, coverImageURL: ${state.coverImageURL}`)
    setCoverImageURL(state.coverImageURL)
}

>Solution :

If the parameters are passed in and useLocation().state has value, your condition is true. This is what you expect.

The problem is setting state causes a re-render of the component (setCoverImageUrl()). When the component re-renders, your condition is still true. This means you set state again, and therefore re-render.

This is why you see "too many re-renders", because you have an infinite loop.

To fix this, put your condition and state update in a useEffect that only triggers when the component first mounts:

React.useEffect(() => {
  if(!!state && 'project' in state && 'coverImageURL' in state) { // parameters passed
    project = state.project
    console.log(`parameters supplied, coverImageURL: ${state.coverImageURL}`)
    setCoverImageURL(state.coverImageURL)
  }
}, []);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading