Corey Brooks

Corey Brooks

1564825720

React + Redux + Comlink = Off-main-thread

Redux is state management. State management belongs off the main thread.

React is a popular web framework.Some love React for its component abstraction, some because of its vast ecosystem and some for its meta-platform properties.

Architecture

To me, React — just like Preact, Svelte or lit-html — provide mainly one feature of interest: Turning state into DOM, ideally in an efficient manner. Your business logic manipulates a state object and your UI framework consumes said object to update your UI accordingly. These frameworks enable you to have a clear separation between state and UI. Nonetheless, I often see people encapsulate their business logic into their (visual) components tied to component-internal state. This is where Redux can help. Redux is a popular “state container”, centralizing your state and all its mutations in one place, outside your components, reenforcing the aforementioned separation.

State management is not UI work and consequently Redux should not be running on the UI thread! Since I have not written React or Redux myself 😱, I figured I’d use the canonical sample for pretty much every UI framework out there: TodoMVC. And of course, Redux has a Todo MVC sample!

CRArgh

The problem with Redux’s TodoMVC sample is that it uses create-react-app. I don’t mean that CRA is inherently bad. Not at all. But CRA’s default build setup doesn’t support workers yet, which is kinda essential for this experiment. I did try and use the branch from that PR, but it doesn’t seem to be fully working yet.

Alternatively, you can “eject” from CRA and take matters into your own hands. Ejecting brings everything from under the hood to... well, over the hood, I guess. After doing so I found myself way out of my depth. The webpack and babel configs are impenetrable to me, which is mostly due to my lack of experience with webpack and babel. The bottom line here is that I couldn’t easily adjust Redux’s TodoMVC sample to support workers.

Note: webpack is not optimal for workers, as it cannot share chunks between main thread and workers. I opened an issue for this a while ago and talked to Sean Larkin about it quite recently. It seems webpack 5 will make solving this much easier. But let me be clear: webpack is an acceptable choice for OMT, as long as you keep an eye on the amount of double-loading that you are potentially causing. If you are using webpack and want to use workers, Jason wrote worker-plugin, which teaches webpack about the new Worker() constructor to make workers easy to use.

The bottom line is that I couldn’t really do this with CRA, so for the purpose of this blog post I used Rollup, as I am familiar with that and even maintain an off-main-thread plugin for Rollup. All in all it doesn’t really matter which build system you use.

Business as usual

To have a starting point, I whipped up a useless counter app. It has a counter. You can increment and decrement it. That’s it. No bells and whistles. It uses Redux for state management, React for the UI and react-redux as the glue between the two. Let’s look at some code: Our state is just a counter. We have two actions we can perform: Incrementing and decrementing that counter.

const reducer = (state = 0, { type }) => {
 switch (type) {
 case "INCREMENT":
 return state + 1;
 case "DECREMENT":
 return state - 1;
 default:
 return state;
 }
};

const store = createStore(reducer);

This store variable contains our state container. Through this store we can subscribe() to state changes or dispatch() actions to mutate the state. The (important parts of the) store’s interface looks like this:

interface Store {
dispatch(action): void;
getState(): State;
subscribe(listener: () => void): UnsubscribeFunc;
}

For our main app component CounterDemo, we are going to write some vanilla HTML and connect() the resulting component to our state store:

const CounterDemo = connect(counter => ({ counter }))(
({ counter, dispatch }) => (
<div>
<h1>Welcome</h1>
<p>The current counter is: {counter}</p>
<button onClick={() => dispatch({ type: “INCREMENT” })}>+</button>
<button onClick={() => dispatch({ type: “DECREMENT” })}>-</button>
</div>
)
);

As a last step, we need to render our main app component wrapped by react-redux’s <Provider> component:

ReactDOM.render(
<Provider store={store}>
<CounterDemo />
</Provider>,
document.getElementById(“root”)
);

And voilà, we have a beautiful counter app. You can find the full code for this demo in a gist.

Comlinking it

As the app is fairly simple, so is our reducer. But even for bigger apps state management is rarely bound to the main thread in my experience. Everything we are doing can also be done in a worker as we are not using any main-thread-only API like the DOM. So let’s remove all of the Redux code from our main file and put it in a new file for our worker. Additionally, we are going to pull in Comlink.

Comlink is a library to make web workers enjoyable. Instead of wrangling postMessage(), Comlink implements the (surprisingly old) concept of RPC with the help of proxies. Comlink will give you a proxy and that proxy will “record” any actions (like method invocations) performed on it. Comlink will send these records to the worker, replay them against the real object and send back the result. This way you can work on an object on the main thread even though the real object lives in a worker.

With this in mind, we can move store to a worker and proxy it back to the main thread:

// worker.js
import { createStore } from “redux”;
import { expose } from “comlink”;

const reducer = (state = 0, { type }) => {
// … same old …
};

const store = createStore(reducer);
expose(store);

On the main thread, we’ll create a worker using this file and use Comlink to create the proxy:

// main.js
import { wrap } from “comlink”;

const remoteStore = wrap(new Worker(“./worker.js”));
const store = remoteStore;

ReactDOM.render(
<Provider store={store}> <CounterDemo /> <//>,
document.getElementById(“root”)
);
// … same old …

remoteStore has all the methods and properties that the store has, but everything is async. More concretely that means that remoteStore’s interface looks like this:

interface RemoteStore {
dispatch(action): Promise<void>;
getState(): Promise<State>;
subscribe(listener: () => void): Promise<UnsubscribeFunc>;
}

The reason for this is the nature of RPC. Every method invocation is turned into a postMessage() by Comlink and it has to wait for the worker to come back with a reply. This process is inherently asynchronous. The advantage is that we just moved all processing into the worker, away from the main thread. We can use the remoteStore the same way we would store. We just have to remember to use await whenever we call a method.

Problems

As the interface shows, subscribe() expects a callback as a parameter. But functions can’t be sent via postMessage(), so this would throw. For this reason Comlink provides proxy(). Wrapping a value in proxy() will cause Comlink to not send the value itself but a proxy instead. So it’s like Comlink using itself.

Another problem is that getState() is expected to return a value synchronously, but Comlink has made it asynchronous. To solve this we’ll have to get our hands dirty and keep a local copy of the most recent state value we have received.

Let’s put all these two fixes in a wrapper for remoteStore:

export default async function remoteStoreWrapper(remoteStore) {
const subscribers = new Set();

let latestState = await remoteStore.getState();
remoteStore.subscribe(
proxy(async () => {
latestState = await remoteStore.getState();
subscribers.forEach(f => f());
})
);
return {
dispatch: action => remoteStore.dispatch(action),
getState: () => latestState,
subscribe(listener) {
subscribers.add(listener);
return () => subscribers.delete(listener);
}
};
}

Note: You might have noticed that I re-implemented subscribe() here rather than just calling remoteStore.subscribe(). The reason is that there is a long-standing issue with Comlink: When one end of a MessageChannel gets garbage collected, most browsers are not able to garbage collect the other end, permanently leaking memory. Considering that proxy() creates a MessageChannel and that subscribe() might get called quite a lot, I opted to re-implement the subscription mechanism to avoid building up leaked memory. In the future, WeakRefs will help Comlink address this problem.

In our main file, we have to use this wrapper to turn our RemoteStore into something that is fully compatible to Store:

- const store = remoteStore;

  • const store = await remoteStoreWrapper(remoteStore);

With all of that in place, we can run our app. Everything should look and behave the same, but Redux is now running off-main-thread.

You can find the full code in a gist.

Conclusion

Comlink can help you move logic to a worker without buying into a massive refactor. I did take some shortcuts here (like ignoring the return value of remoteStore.subscribe()), but all-in-all this is a web app that makes good use of a worker. Not only is the business logic separated from the view, but the processing of state is not costing us any precious main thread budget. Additionally, moving your state management to a worker means that all the parsing for the worker’s dependencies is happening off-main-thread as well.

Thanks for reading

If you liked this post, share it with all of your programming buddies!

Follow us on Facebook | Twitter

Further reading about React, Redux and Django

React - The Complete Guide (incl Hooks, React Router, Redux)

Modern React with Redux [2019 Update]

Best 50 React Interview Questions for Frontend Developers in 2019

JavaScript Basics Before You Learn React

Microfrontends — Connecting JavaScript frameworks together (React, Angular, Vue etc)

Reactjs vs. Angularjs — Which Is Best For Web Development

React + TypeScript : Why and How

How To Write Better Code in React

React Router: Add the Power of Navigation

Getting started with React Router

Using React Router for optimizing React apps

#reactjs #redux

What is GEEK

Buddha Community

React + Redux + Comlink = Off-main-thread
Autumn  Blick

Autumn Blick

1598839687

How native is React Native? | React Native vs Native App Development

If you are undertaking a mobile app development for your start-up or enterprise, you are likely wondering whether to use React Native. As a popular development framework, React Native helps you to develop near-native mobile apps. However, you are probably also wondering how close you can get to a native app by using React Native. How native is React Native?

In the article, we discuss the similarities between native mobile development and development using React Native. We also touch upon where they differ and how to bridge the gaps. Read on.

A brief introduction to React Native

Let’s briefly set the context first. We will briefly touch upon what React Native is and how it differs from earlier hybrid frameworks.

React Native is a popular JavaScript framework that Facebook has created. You can use this open-source framework to code natively rendering Android and iOS mobile apps. You can use it to develop web apps too.

Facebook has developed React Native based on React, its JavaScript library. The first release of React Native came in March 2015. At the time of writing this article, the latest stable release of React Native is 0.62.0, and it was released in March 2020.

Although relatively new, React Native has acquired a high degree of popularity. The “Stack Overflow Developer Survey 2019” report identifies it as the 8th most loved framework. Facebook, Walmart, and Bloomberg are some of the top companies that use React Native.

The popularity of React Native comes from its advantages. Some of its advantages are as follows:

  • Performance: It delivers optimal performance.
  • Cross-platform development: You can develop both Android and iOS apps with it. The reuse of code expedites development and reduces costs.
  • UI design: React Native enables you to design simple and responsive UI for your mobile app.
  • 3rd party plugins: This framework supports 3rd party plugins.
  • Developer community: A vibrant community of developers support React Native.

Why React Native is fundamentally different from earlier hybrid frameworks

Are you wondering whether React Native is just another of those hybrid frameworks like Ionic or Cordova? It’s not! React Native is fundamentally different from these earlier hybrid frameworks.

React Native is very close to native. Consider the following aspects as described on the React Native website:

  • Access to many native platforms features: The primitives of React Native render to native platform UI. This means that your React Native app will use many native platform APIs as native apps would do.
  • Near-native user experience: React Native provides several native components, and these are platform agnostic.
  • The ease of accessing native APIs: React Native uses a declarative UI paradigm. This enables React Native to interact easily with native platform APIs since React Native wraps existing native code.

Due to these factors, React Native offers many more advantages compared to those earlier hybrid frameworks. We now review them.

#android app #frontend #ios app #mobile app development #benefits of react native #is react native good for mobile app development #native vs #pros and cons of react native #react mobile development #react native development #react native experience #react native framework #react native ios vs android #react native pros and cons #react native vs android #react native vs native #react native vs native performance #react vs native #why react native #why use react native

Reduce Redux Boilerplate Code with Redux-Actions

Redux has become one of the most popular libraries in front-end development since it was introduced by Dan Abramov and Andrew Clark in 2015. They designed it as the successor for Flux, with the support of some developer tools and a few more concepts embedded in it.

Flux is a fancy name for observer pattern further modified to support React. Both Flux and Redux consist of similar concepts like Store, Actions (events in the application). In other words, Flux is a simple JavaScript object but with some middleware like redux-thunk. It can be a function or a promise for Redux. However, Redux is a single source of truth with concepts like immutability, which improve performance. It is one of the main reasons for Redux to dominate in State Management.

Image for post

Flux vs Redux comparison source: enappd.com

Despite its advantages, some developers have found it rather challenging to deal with Redux due to the amount of boilerplate code introduced with it. And the complexity of the code seems to be another reason for the difficulty.

In this article, we will look at how to reduce the boilerplate code brought about by Actions and Reducers using Redux-Actions

#react-redux-boilerplate #react-redux #react #react-actions #redux

Karine  Crooks

Karine Crooks

1589960215

A Basic Redux Setup in React/React Native

Redux is a powerful state management tool that can be very useful as your React or React Native application grows and requires you to keep track of more state. How you want to set up Redux is up to you, but if you’re a beginner, it may be easiest to learn the flow of Redux with a step-by-step walkthrough. Here I’ve outlined a basic way to set up Redux to go along with this post and it will be the same for React and React Native.

#react #react-native #redux #react-redux

Aubrey  Price

Aubrey Price

1590485641

Accessing Redux from Components In React & React Native

How to set up a basic version of Redux in your React or React Native application. To make things clearer, I based my setup on my event application, where users create events that other users attend. We generated the action creators, reducers, and Redux store, and wrapped the application in a provider. Today I’ll finish the loop and talk about how to access the Redux store in your application using both class and functional components. The provider we added to the root component provides the store to all the components in your application. Therefore, we will just look at how to access the store from an individual component.

#react-redux #redux #hooks #react #react-native

Neal  Bode

Neal Bode

1601294220

React Native Redux | How To Use Redux In React Native

React Native Redux Example | How To Use Redux In React Native is today’s leading topic. Redux is a standalone state management library, which can be used with any library or framework. If your background is React developer, then you have used the Redux library with React.

Overview of React Native Redux Example

  • Step 1: Install React Native on mac.
  • Step 2: Add TextBox and Button.
  • Step 3: Define the state and input handler.
  • Step 4: Create actions, reducers, and components folder.
  • Step 5: Create a Reducer function.
  • Step 6: Create a Redux store.
  • Step 7: Pass the store to the React Native app.
  • Step 8: Connect React Native app to the Redux store.

React Native Redux Example Tutorial

The primary use of Redux is that we can use one application state as a global state and interact with the state from any react component is very easy, whether they are siblings or parent-child. Now, let us start the React Native Redux Example Tutorial by installing React Native on Mac first.

We start our project by installing React Native CLI globally on the Mac. You can skip the following command if you have already installed it.

#react native #react native cli #react native on mac #redux #react developer