'React initial state delay [closed]
I have a React project and I am fetching data from firebase directly on the client side. For the components that are using an initial state (which is usually set from firestore data), there is like 1 second delay on the component until the data is visible. For example, I have a paragraph "Welcome {username}". Username is being set in the useEffect by calling a function that fetches data from firestore. At first it appears blank and after 1 second, let's say, the username is visible. Is there anything I can do to fix this? I know it is due to the setState, but I am wondering if there is any fix.
Solution 1:[1]
I think that what you are looking for is not a fix, but a way to display things once they've been loaded.
What I would suggest is a conditional display. Something like :
const [username, setUsername] = useState(null);
useEffect(() => {
yourMethodThatSetUsername();
}, [])
return (
{
username ? <YourComponent /> : null
}
)
Solution 2:[2]
Usually you set a state in the component from which you are calling useEffect, like this:
[loading, setLoading] = useState(true);
You can then conditionally render your component like this:
loading ? //some progress component
: Welcome ${username};
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | humblots |
| Solution 2 | bitBender |
