All Articles

Lazy loading with React

Lazy loading with React

React is amazing. I love it. One use case it handles very well is lazy loading data.

What is lazy loading?

Lazy loading basically means you load some of your app / page later so your page feels like it’s loading faster.

Maybe you defer loading the bottom half of the page, or all the images until after a certain event has happened. It could be a user event like scroll, click, or a browser event like “page loaded”.

The whole point is that you’re deferring some of the loading so the web page loads faster.

A simple-ish example

https://codesandbox.io/s/v312zpolm3

Lazy loading in action

Let’s talk about the interesting piece: render()

render() method

First,loadingMsg will be empty if the content exists in this.state else it’ll show the Loading... message.

Then, <BodyContent/> component will only be rendered if this.state.content has been set, which happens in componentDidMount() after the ajax call is complete.

Checking for state prop existence is a great way to conditionally load content, as shown above.

To sum up: On first render, we show the <h2> tag and the Loading... message because this.state.content hasn’t been set yet. Then, after first render completes, React calls componentDidMount() and makes the ajax call. After success, this.setState() updates this.state which triggers a re-render. Then we see our new content. So good!

More use cases

In the above example, we’re loading our data as soon as the component has rendered on the page. Instead of waiting for the mount event, you could instead wait for a user event, for instance a Load content button click.

Showing “Load content” button for lazy loading

Any questions / comments?