A walk through React experimental features

Jonatan Salas
3 min readMar 4, 2018

Disclaimer: The code pasted here may vary from the code that Dan exposed in his talk.

Recently Dan Abramov gave a talk at JSConf in Iceland where he shows all the new fancy things that they’re working with the React Team.

Here is the video from JSConf Iceland

In his talk, he introduces us to some kind of new experimental features that React Team is prototyping, and they are:

  • Time Slicing
  • Suspense

Time Slicing

Time Slicing let React doesn’t block the Main Thread while rendering.

Time Slicing is powered by React Fiber architecture + requestIdleCallback. The basic features behind Fiber architecture are the following ones:

  • Pause work and come back to it later.
  • Assign priority to different types of work.
  • Reuse previously completed work.
  • Abort work if it’s no longer needed.

If you want to have a deeper understand of how it works, you can read here.

Suspense

Suspense is the ability to pause any state update in order to wait for data to load.

Suspense is a new api that works in the following way:

Here you can see how we create a fetcher by passing a function that returns a Promise

You create a fetcher function using createResource from the package simple-cache-provider. Simple Cache Provider is a first API prototype, it may change in the future.

When calling createResource you need to pass a function that returns a Promise.

Then you can use that fetcher function from inside of render or getDerivedStateFromProps.

Here you have two versions of the same component calling fetcher from render, and from getDerivedStateFromProps:

You can see how it’s the code, but, how it works under the hood? Let me explain what happens when you use the fetcher function:

  • The fetcher function always receive the cache, so it attempts to read a value from it. The cache is shared for over the whole tree by using new React Context.
  • If the value isn’t present, it throws a function that returns a Promise and then sets the result on the cache.
  • React keeps doing work while waiting for you data to load.
  • When data finish loading, it applies the pending updates and the view is finally rendered.

Suspense will provide lower and higher level APIs. Currently, there’s a need for new Primitives to born, like Dan’s Placeholder Component, and deferSetState.

We use Placeholder to capture the throw by the fetcher and know the state of the data that’s being loaded.
withCache is a HOC that connects with SimpleCache.Consumer and puts the cache over the wrapped component.

Time Slicing + Suspense = Async Rendering

Demo

I have built a more complex demo that’s published on Github! You can take a look at the code here:

Edit:

I have updated the example app from the repository, it uses a custom Component class with the following implementation.

Custom Component class with deferSetState implementation

Well, that’s all, hope you’ve enjoyed the post.

--

--