React v16.6.0 was released yesterday. Let’s see what this new version means for some use cases that were previously only possible using classes.

Disclaimer: I’m not saying you should try to avoid classes, there’s nothing wrong with using classes for your components.

PureComponent and shouldComponentUpdate

Before React 16.6, if you wanted to tell React that a component didn’t need to be re-rendered you had to extend React.PureComponent or implement shouldComponentUpdate . If your component was a function you had to change it to a class.

With React 16.6 you no longer need to change a function component to a class just to use React.PureComponent or shouldComponentUpdate . There’s a new function React.memo() that provides the same functionality and can be used with function components:

From React Docs

Fetching data in componentDidMount

Another reason to change function components to classes is when you need to use componentDidMount to fetch stuff. Fetching data from a component usually looks like this:

React 16.6 discreetly introduced a new component: <Suspense/> . This component will shine when the new React Concurrent Mode is stable, and it shouldn’t be used for anything else than React.lazy() at this moment (until react-cache is stable). In other words:

That said, let me show you how to get rid of the componentDidMount (and the need for a class) using <Suspense/> :

Explaining how <Suspense/> works requires its own (very long) post, so you’ll have to trust me that this works in a similar way to the class component:

the first time it’s rendered a fetch will be triggered (like with componentDidMount ),

), a fallback is rendered until the fetch finishes (like with state.loading ),

), and the component is re-rendered once the fetch finishes (like with setState ).

If you want to know what fetchWithCache is doing open this codesandbox.

Update after #ReactConf2018 keynote

What about the rest of the cases where we need classes? Looks like we will only have to wait to the next minor release of React (or try react@16.7.0-alpha):

That’s all. Thanks for reading.

Clap or share it if you liked it.