Rajat Sharma
Rajat Sharma

Reputation: 106

Pre-loading data in React

What is the best approach for pre-loading data before navigation to a route in react?

Shall we do it using a HOC, or fetch data in componentDidMount method(asynchronously using thunk) and show spinner until data is fetched, or is there a better way ?

Upvotes: 1

Views: 732

Answers (2)

Tarun Nagpal
Tarun Nagpal

Reputation: 700

I would prefer to write your API calls in componentDidMount() and show the spinner till the content is loaded.

But you should also take care of the following things.

  1. Do not load all API in root/main component.
  2. List item into the components wherever needed.

This approach will help us reduce the page load time and performance.

Upvotes: 1

AlexanderKaran
AlexanderKaran

Reputation: 525

There are many ways to load data and most of these come down to personal preference. In web based applications I lean towards loading the whole page straight away and only showing a spinner or loading animation where I am fetching data. By taking this approach people don’t think the app is stuck as the whole page loaded.

For example if I have a table on page that fetches user data, I show an animation in the table saying data is loading.

A nice of fetching the data is building a custom hook that returns a loading state and the data.

Upvotes: 2

Related Questions