Playing with React Hooks and Web Workers

Daishi Kato
3 min readJan 29, 2019

You can try that too.

Introduction

React Hooks is something I’ve been working on lately. What’s wonderful is creating custom hooks. If you encapsulate logic nicely in a hook, it can be shared among components and used intuitively. You can find my custom hooks in my GitHub repos, some of which are very experimental.

This time, my experiment is to combine React Hooks and Web Workers. I know it’s not too difficult, but let me explain a bit in this short article.

The custom hook

Let me first introduce the library. It’s called “react-hooks-worker”. We won’t go into details about the implementation, but it’s pretty simple. Check out the code if you are interested.

How to use it

You first need a worker script. It’s somewhat a different way of writing, compared to scripts for browsers. Basically, it receives a message and sends a message. Messages are typically serializable. Note that message passing does not have to be a request/response…

--

--