JavaScript
x
6
1
useLayoutEffect(() => {
2
getUser()
3
.then(res => setGlobalUser(res.data))
4
.catch(err => console.log(err))
5
})
6
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:
JavaScript
1
11
11
1
useEffect(() => {
2
getUser()
3
.then(res => setGlobalUser(res.data))
4
.catch(err => console.log(err))
5
})
6
7
if(!globalUser) {
8
// you can return a loader here if you want
9
return null;
10
}
11