The most important question is: what do you mean by 'loading'? If you are talking about the physical element being mounted, some of the first answers here are great. However, if the first thing your app does is check for authentication, what you are really loading is data from the backend whether the user passed a cookie that labels them an authorized or unauthorized user.
This is based around redux, but you can do easily change it to plain react state model.
action creator:
export const getTodos = () => {
return async dispatch => {
let res;
try {
res = await axios.get('/todos/get');
dispatch({
type: AUTH,
auth: true
});
dispatch({
type: GET_TODOS,
todos: res.data.todos
});
} catch (e) {
} finally {
dispatch({
type: LOADING,
loading: false
});
}
};
};
The finally part means whether the user is authed or not, the loading screen goes away after a response is received.
Here's what a component that loads it could look like:
class App extends Component {
renderLayout() {
const {
loading,
auth,
username,
error,
handleSidebarClick,
handleCloseModal
} = this.props;
if (loading) {
return <Loading />;
}
return (
...
);
}
...
componentDidMount() {
this.props.getTodos();
}
...
render() {
return this.renderLayout();
}
}
If state.loading is truthy, we will always see a loading screen. On componentDidMount, we call our getTodos function, which is an action creator that turns state.loading falsy when we get a response (which can be an error). Our component updates, calls render again, and this time there is no loading screen because of the if statement.