Skip to content
Advertisement

Updating state using api in useLayoutEffect does not work before painting component

useLayoutEffect(() => {
  getUser()
    .then(res => setGlobalUser(res.data))
    .catch(err => console.log(err))
})

The getUser method exists for API calls. I am trying to display the user profile when the user refreshes the website. That’s why I used useLayoutEffect because I wanted to update the globalUser state before painting and then show it when the web page is painted.

But the globalUser state value is null when I refresh the page, then quickly re-render then show the user profile information on the web page.

Advertisement

Answer

useLayoutEffect is a hook mainly to read the layout of a component before painting. It’s not designed for data fetching. What you want can be achieved with useEffect and a conditional rendering. As an example like so:

useEffect(() => {
  getUser()
    .then(res => setGlobalUser(res.data))
    .catch(err => console.log(err))
})

if(!globalUser) {
  // you can return a loader here if you want
  return null;
}
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement