Sometimes, we want to display a loading screen while the DOM is rendering with React.
In this article, we’ll look at how to display a loading screen while the DOM is rendering with React.
Display a Loading Screen While the DOM is Rendering with React
To display a loading screen while the DOM is rendering with React, we can add a loading state into our React component.
Then we can display what we want depending on whether the component is done loading or not.
For example, we can write:
import React, { useEffect, useState } from "react";
export default function App() {
const [loading, setLoading] = useState(true);
useEffect(() => {
setTimeout(() => {
setLoading(false);
}, 2000);
}, []);
return <div>{loading ? "loading..." : "hello"}</div>;
}
We have the loading
state that we created with the useState
hook.
Then we call the useEffect
hook with a callback that calls setLoading
with false
to set loading
to false
.
And in the return
statement, we return 'loading...'
is loading
is true
and 'hello'
otherwise.
Conclusion
To display a loading screen while the DOM is rendering with React, we can add a loading state into our React component.
Then we can display what we want depending on whether the component is done loading or not.