Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rendering React components with WebWorkers

I saw some stuff online about rendering React components with HTML5 WebWorkers..even Pete Hunt the head honcho behind React was talking about it.

I have some CPU intensive work over each element of an array followed by a React render of each element of the array, so I am thinking about putting each of those in a WebWorker and then posting the HTML string back to the main UI thread.

My question is - it looks like React.renderToString is deprecated in favor of ReactDOMServer.renderToString...so I ask all of you and Pete Hunt - are we supposed to use ReactDOMServer on the front-end if we wish to use WebWorkers to render React components or is there another recommended approach?

(The reason of course, is we can only pass strings / serialized data between threads in JS, so the idea is to render the React component to a string, then pass it back to the main UI thread as a string.)

like image 597
Alexander Mills Avatar asked Dec 17 '15 00:12

Alexander Mills


People also ask

How do you render components dynamically in React?

Dynamic component rendering with React To allow us to render a JSON by dynamic components using their name we first have to loop through the array of components itself. Below you can see that we're using the map function to do exactly that.

Can Webworkers modify Dom?

You can run whatever code you like inside the worker thread, with some exceptions. For example, you can't directly manipulate the DOM from inside a worker, or use some default methods and properties of the window object.

Can you render multiple components in React?

React allows us to render one component inside another component. It means, we can create the parent-child relationship between the 2 or more components. Prerequisites: The pre-requisites for this project are: React Knowledge.


1 Answers

I wrote up a quick implementation of React, rendering in a Web worker. It is not really a renderToString, but more like a custom renderer. I also found that this is much faster than the normal implementation.

The demo page has 2 applications - an example showing a CPU intensive app, and a simple TODO list with events.

Here are the performance numbers too -http://blog.nparashuram.com/2016/02/using-webworkers-to-make-react-faster.html

like image 130
axemclion Avatar answered Sep 24 '22 15:09

axemclion