Home > Net >  Too Many Rerenders - Storing useLocation().state variable in a useState() variable
Too Many Rerenders - Storing useLocation().state variable in a useState() variable

Time:03-11

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.

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

CodePudding user response:

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)
  }
}, []);
  • Related