Coaction - An efficient and flexible state management library for building high-performance, multithreading web applications.
Repo: https://github.com/unadlib/coaction
Motivation
Modern web applications are becoming increasingly complex, pushing the boundaries of what's possible in the browser. Single-threaded JavaScript, while powerful, often struggles to keep up with the demands of sophisticated UIs, real-time interactions, and data-intensive computations. This bottleneck leads to performance issues, laggy or unresponsive interfaces, limitations in request connections, and ultimately, a compromised user experience.
While Web Workers (or SharedWorker) offer a path towards parallelism and improved performance, they introduce a new set of challenges. Managing state across threads, synchronizing data efficiently, and maintaining coherent application logic can quickly become a daunting task. Existing state management solutions often fall short in addressing these specific needs, either by being too tightly coupled to the worker thread or by introducing complex abstractions that hinder developer productivity.
Coaction was created out of the need for a state management solution that truly embraces the multithreading nature of modern web applications. It recognizes that performance and developer experience shouldn't be mutually exclusive. By leveraging the power of Web Workers and Shared Workers, Coaction allows developers to offload computationally intensive tasks and state management logic from the worker thread, resulting in a more responsive and fluid user interface.
More than just performance, Coaction is about enabling a more scalable and maintainable architecture for complex applications. The library's intuitive API, inspired by Zustand, ensures a smooth learning curve and a productive development workflow. Its support for Slices, namespaces, and computed properties promotes modularity and code organization, making it easier to manage large and evolving codebases.
Coaction's integration with data-transport unlocks a new level of flexibility in state synchronization. By supporting generic transport protocols, it opens up possibilities for various communication patterns and architectures, catering to the unique needs of different applications.
In essence, Coaction empowers developers to build the next generation of web applications without sacrificing performance, developer experience, or architectural integrity. It bridges the gap between the increasing complexity of web applications and the need for efficient, maintainable, and performant state management across threads. It's a tool designed for developers who strive to create exceptional user experiences in a world where parallelism and responsiveness are no longer optional, but essential. It also supports remote synchronization, making it suitable for building any CRDTs application as well.
Concepts and Features
Coaction aims to provide a secure and efficient solution for sharing and synchronizing state in multithreading environments (such as Web Workers, Shared Workers, or even across processes and devices) in web applications.
Key features include:
- Multithreading Sync: Supports sharing state between webpage thread and the worker thread. With data-transport for generic communication, developers can avoid the complexities of message passing and serialization logic.
- Immutable State with Optional Mutability: Powered by the Mutative library, the core provides an immutable state transition process while allowing performance optimization with mutable instances when needed.
- Patch-Based Updates: Enables efficient incremental state changes through patch-based synchronization, simplifying its use in CRDTs applications.
- Built-in Computed: Supports derived properties based on state dependencies, making it easier to manage and retrieve computed data from core states.
- Slices Pattern: Easily combine multiple slices into a store with namespace.
- Extensible Middleware: Allows for middleware to enhance the store's behavior, such as logging, time-travel debugging, or integration with third-party tools.
- Integration with 3rd-Party Libraries: Supports popular frameworks like React, Angular, Vue, Svelte, and Solid, as well as state management libraries such as Redux, Zustand, and MobX.
Operating Modes and Fundamentals
This library operates in two primary modes:
- Standard Mode
- In a standard webpage environment, the store is managed entirely within the webpage thread. Patch updates are disabled by default to ensure optimal performance in standard mode.
- Shared Mode
- The worker thread serves as the primary source of the shared state, utilizing transport for synchronization.
- Webpage thread act as clients, accessing and manipulating the state asynchronously through a store.
In shared mode, the library automatically determines the execution context based on the transport parameters, handling the synchronization thread seamlessly.
You can easily use Coaction in your application to support multiple tabs, multithreading, or multiprocessing.
For example, for a 3D scene shared across several tabs, you can effortlessly handle their state management using Coaction.
https://github.com/user-attachments/assets/9eb9f4f8-8d47-433a-8eb2-85f044d6d8fa
Shared Mode - Sequence Diagram
sequenceDiagram participant Client as Webpage Thread (Client) participant Main as Worker Thread (Main) activate Client Note over Client: Start Worker Thread activate Main Client ->> Main: Trigger fullSync event after startup activate Main Main -->> Client: Synchronize data (full state) deactivate Main Note over Client: User triggers a UI event Client ->> Main: Send Store method and parameters activate Main Main ->> Main: Execute the corresponding method Main -->> Client: Synchronize state (patches) Note over Client: Render new state Main -->> Client: Asynchronously respond with method execution result deactivate Main deactivate Client
Performance
Measure(ops/sec) to update 10K arrays, bigger is better(view source).
Library | Test Name | Ops/sec |
---|---|---|
@coaction/mobx | bigInitWithoutRefsWithoutAssign | 37.07 |
mobx | bigInitWithoutRefsWithoutAssign | 37.50 |
coaction | bigInitWithoutRefsWithoutAssign | 19,910 |
mobx-keystone | bigInitWithoutRefsWithoutAssign | 7.88 |
@coaction/mobx | bigInitWithoutRefsWithAssign | 1.53 |
mobx | bigInitWithoutRefsWithAssign | 10.77 |
coaction | bigInitWithoutRefsWithAssign | 3.01 |
mobx-keystone | bigInitWithoutRefsWithAssign | 0.13 |
@coaction/mobx | bigInitWithRefsWithoutAssign | 14.66 |
mobx | bigInitWithRefsWithoutAssign | 16.11 |
coaction | bigInitWithRefsWithoutAssign | 152 |
mobx-keystone | bigInitWithRefsWithoutAssign | 2.44 |
@coaction/mobx | bigInitWithRefsWithAssign | 0.98 |
mobx | bigInitWithRefsWithAssign | 8.81 |
coaction | bigInitWithRefsWithAssign | 3.83 |
mobx-keystone | bigInitWithRefsWithAssign | 0.11 |
@coaction/mobx | init | 37.34 |
mobx | init | 42.98 |
coaction | init | 3,524 |
mobx-keystone | init | 40.48 |
This table benchmarks various state management libraries on large initialization tasks. Coaction stands out dramatically, performing at least hundreds of times faster in certain scenarios. For example, in the "bigInitWithoutRefsWithoutAssign" test, Coaction achieves about 19,910 ops/sec compared to Mobx’s 37.5 ops/sec—over 500 times faster. Similarly, in the "init" test, Coaction reaches around 3,524 ops/sec versus Mobx's 42.98 ops/sec—an increase of roughly 80 times. These results highlight Coaction's exceptional efficiency in handling large-scale data initialization.
We will also provide more complete benchmarking.
Installation
You can install @coaction/react for React application via npm, yarn, or pnpm.
sequenceDiagram participant Client as Webpage Thread (Client) participant Main as Worker Thread (Main) activate Client Note over Client: Start Worker Thread activate Main Client ->> Main: Trigger fullSync event after startup activate Main Main -->> Client: Synchronize data (full state) deactivate Main Note over Client: User triggers a UI event Client ->> Main: Send Store method and parameters activate Main Main ->> Main: Execute the corresponding method Main -->> Client: Synchronize state (patches) Note over Client: Render new state Main -->> Client: Asynchronously respond with method execution result deactivate Main deactivate Client
If you want to use the core library without any framework, you can install coaction via npm, yarn, or pnpm.
npm install coaction @coaction/react
Usage
Standard Mode Store
npm install coaction
Shared Mode Store
counter.js:
import { create } from '@coaction/react'; const useStore = create((set, get) => ({ count: 0, increment: () => set((state) => state.count++) })); const CounterComponent = () => { const store = useStore(); return ( <div> <p>Count: {store.count}</p> <button onClick={store.increment}>Increment</button> </div> ); };
worker.js:
import { create } from '@coaction/react'; export const counter = (set) => ({ count: 0, increment: () => set((state) => state.count++) });
import { create } from '@coaction/react'; import { counter } from './counter'; const useStore = create(counter);
Slices Pattern And Derived Data
import { create } from '@coaction/react'; const worker = new Worker(new URL('./worker.js', import.meta.url)); const useStore = create(counter, { worker }); const CounterComponent = () => { const store = useStore(); return ( <div> <p>Count in Worker: {store.count}</p> <button onClick={store.increment}>Increment</button> </div> ); };
Conclusion
In essence, Coaction empowers developers to build the next generation of web applications without sacrificing performance, developer experience, or architectural integrity. It bridges the gap between the increasing complexity of web applications and the need for efficient, maintainable, and performant state management across threads. It's a tool designed for developers who strive to create exceptional user experiences in a world where parallelism and responsiveness are no longer optional, but essential. It also supports remote synchronization, making it suitable for building any CRDTs application as well.
Repo: https://github.com/unadlib/coaction
The above is the detailed content of Unlocking Multiprocessing for Smoother Web Applications. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Java and JavaScript are different programming languages, each suitable for different application scenarios. Java is used for large enterprise and mobile application development, while JavaScript is mainly used for web page development.

JavaScriptcommentsareessentialformaintaining,reading,andguidingcodeexecution.1)Single-linecommentsareusedforquickexplanations.2)Multi-linecommentsexplaincomplexlogicorprovidedetaileddocumentation.3)Inlinecommentsclarifyspecificpartsofcode.Bestpractic

The following points should be noted when processing dates and time in JavaScript: 1. There are many ways to create Date objects. It is recommended to use ISO format strings to ensure compatibility; 2. Get and set time information can be obtained and set methods, and note that the month starts from 0; 3. Manually formatting dates requires strings, and third-party libraries can also be used; 4. It is recommended to use libraries that support time zones, such as Luxon. Mastering these key points can effectively avoid common mistakes.

PlacingtagsatthebottomofablogpostorwebpageservespracticalpurposesforSEO,userexperience,anddesign.1.IthelpswithSEObyallowingsearchenginestoaccesskeyword-relevanttagswithoutclutteringthemaincontent.2.Itimprovesuserexperiencebykeepingthefocusonthearticl

JavaScriptispreferredforwebdevelopment,whileJavaisbetterforlarge-scalebackendsystemsandAndroidapps.1)JavaScriptexcelsincreatinginteractivewebexperienceswithitsdynamicnatureandDOMmanipulation.2)Javaoffersstrongtypingandobject-orientedfeatures,idealfor

Event capture and bubble are two stages of event propagation in DOM. Capture is from the top layer to the target element, and bubble is from the target element to the top layer. 1. Event capture is implemented by setting the useCapture parameter of addEventListener to true; 2. Event bubble is the default behavior, useCapture is set to false or omitted; 3. Event propagation can be used to prevent event propagation; 4. Event bubbling supports event delegation to improve dynamic content processing efficiency; 5. Capture can be used to intercept events in advance, such as logging or error processing. Understanding these two phases helps to accurately control the timing and how JavaScript responds to user operations.

JavaScripthassevenfundamentaldatatypes:number,string,boolean,undefined,null,object,andsymbol.1)Numbersuseadouble-precisionformat,usefulforwidevaluerangesbutbecautiouswithfloating-pointarithmetic.2)Stringsareimmutable,useefficientconcatenationmethodsf

If JavaScript applications load slowly and have poor performance, the problem is that the payload is too large. Solutions include: 1. Use code splitting (CodeSplitting), split the large bundle into multiple small files through React.lazy() or build tools, and load it as needed to reduce the first download; 2. Remove unused code (TreeShaking), use the ES6 module mechanism to clear "dead code" to ensure that the introduced libraries support this feature; 3. Compress and merge resource files, enable Gzip/Brotli and Terser to compress JS, reasonably merge files and optimize static resources; 4. Replace heavy-duty dependencies and choose lightweight libraries such as day.js and fetch
