Code Monkey home page Code Monkey logo

redux-in-worker's Introduction

redux-in-worker

CI npm size discord

Entire Redux in Web Worker

Introduction

Inspired by React + Redux + Comlink = Off-main-thread.

This is still an experimental project. Please give us a feedback to make it stable.

Some key points are:

  • It only sends "diffs" from the worker thread to the main thread.
  • All Objects in a state tree keep the ref equality.
  • It can run middleware in the worker thread. (only non-DOM middleware #2)
  • No async functions are involved.
  • No proxies are involved.

Install

npm install redux-in-worker

Usage

store.worker.js:

import { createStore } from 'redux';
import { exposeStore } from 'redux-in-worker';

const initialState = { count: 0 };
const reducer = (state = initialState, action) => {
  switch (action.type) {
    case 'increment':
      return { ...state, count: state.count + 1 };
    case 'decrement':
      return { ...state, count: state.count - 1 };
    default:
      return state;
  }
};

const store = createStore(reducer);

exposeStore(store);

app.js:

import React from 'react';
import ReactDOM from 'react-dom';
import { Provider, useDispatch, useSelector } from 'react-redux';
import { wrapStore } from 'redux-in-worker';

const initialState = { count: 0 };
const worker = new Worker(new URL('./store.worker', import.meta.url));
const store = wrapStore(worker, initialState);

const Counter = () => {
  const dispatch = useDispatch();
  const count = useSelector(state => state.count);
  return (
    <div>
      count: {count}
      <button type="button" onClick={() => dispatch({ type: 'increment' })}>+1</button>
      <button type="button" onClick={() => dispatch({ type: 'decrement' })}>-1</button>
    </div>
  );
};

const App = () => (
  <Provider store={store}>
    <Counter />
    <Counter />
  </Provider>
);

ReactDOM.render(<App />, document.getElementById('app'));

Examples

The examples folder contains working examples. You can run one of them with

PORT=8080 npm run examples:01_minimal

and open http://localhost:8080 in your web browser.

Blogs

redux-in-worker's People

Contributors

dai-shi avatar dependabot[bot] avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

redux-in-worker's Issues

How to work with Next JS?

Error: Cannot find module 'core-js/modules/es.object.define-property'
Require stack:
- /workspaces/project/node_modules/redux-in-worker/dist/index.js
- /workspaces/project/.next/server/pages/_app.js
- /workspaces/project/node_modules/next/dist/next-server/server/require.js
- /workspaces/project/node_modules/next/dist/next-server/server/load-components.js
- /workspaces/project/node_modules/next/dist/next-server/server/api-utils.js
- /workspaces/project/node_modules/next/dist/next-server/server/next-server.js
- /workspaces/project/node_modules/next/dist/server/next.js
- /workspaces/project/node_modules/next/dist/server/lib/start-server.js
- /workspaces/project/node_modules/next/dist/cli/next-dev.js
- /workspaces/project/node_modules/next/dist/bin/next

Does not work with redux-toolkit (createAsyncThunk)

Hello! Thank you for such a great library. I used redux-toolkit and createAsyncThunk, but there is an error ``Uncaught Error: Actions must be plain objects. Instead, the actual type was: 'function'. You may need to add middleware to your store setup to handle dispatching other values, such as 'redux-thunk' to handle dispatching functions. See https://redux.js.org/tutorials/fundamentals/part-4-store#middleware and https://redux.js.org/tutorials/fundamentals/part-6-async-logic#using-the-redux-thunk-middleware for examples.` Though it is working without redux-in-worker

How to use redux-persist

Hello, I tried to add redux-persist with no luck.

I tried in App.js

const store = wrapStore(new Worker(new URL('./store.worker', import.meta.url)), {});
const persistor = persistStore(store);

but i get the error:
Failed to execute 'postMessage' on 'Worker': function register(key)

When I tried to trace it, sadly I couldn't figure out anything

Any help would be great!

Using "connect"

Is using connect from react-redux is supported? I seem to be always getting undefined when using connect

import { connect } from 'react-redux';
import SomeComponent from './SomeComponent';

// state is undefined ?
const mapStateToProps = (state) => ({
  state,
});

export default connect(mapStateToProps, null)(SomeComponent);

Usage with Redux toolkits defaultMiddleware and configureStore()

Hi,

First off thanks for the great library, it works really well.

My question is, how can we intregrate this with redux toolkits functions?

I'm following the pattern from your router example.

For example, I try something like this:

    innerStore = configureStore({
        reducer,
        preloadedState: {
          ...initialState,
          ...preloadedState,
        },
        enhancers: [enhancer],
      });

And I get some obscure error. Also I tried with getDefaultMiddelware like so:

  const outerStore = wrapStore(worker, undefined, compose(enhancer, ...getDefaultMiddleware()));

If you know how I can integrate these functions it would be great.

Thanks!

Question - Selectors in workers

Hi!

Your library looks very interesting and promising for our use case. We're working on a very big planning application with a lot of data in a redux store.
The state is quite flat and we use selectors (with reduxjs/reselect) to combine several parts of the state to get different filtered and nested data structures optimized for rendering in React. These selectors are the most heavy part of the application.

Would it be possible to move these selectors to a webworker as well?
Would Redux useSelector be able to import the selector from the webworker?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.