Reactivity ‐ Proxy vs Signal - kdaisho/Blog GitHub Wiki
1. Proxy pattern
functionreactive(target){constlisteners=newSet()functionsubscribe(listener){listeners.add(listener)}constproxy=newProxy(target,{get(obj,prop){returnobj[prop]},set(obj,prop,value){obj[prop]=valuelisteners.forEach(listener=>listener())// notify all listenersreturntrue},})return{ proxy, subscribe }}// usage exampleconststate=reactive({count: 0})// subscribe to changesstate.subscribe(()=>{console.log("state changed to:",state.proxy.count)})// updating the valuestate.proxy.count=1// output: state change to: 1state.proxy.count=20// output: state change to: 20
2. Signal pattern
functionsignal(initialValue){letvalue=initialValueconstlisteners=newSet()functionget(){returnvalue}functionset(newValue){value=newValuelisteners.forEach((listener)=>listener())}functionsubscribe(listener){listeners.add(listener)return()=>listeners.delete(listener)// unsubscribe function}return{ get, set, subscribe }}// usage exampleconstcount=signal(0)// subscribe to changescount.subscribe(()=>{console.log("count updated to:",count.get())})// update the valuecount.set(1)// output: count updated to: 1count.set(200)// output: count updated to: 200
Key takeaways
1. Conceptual basis
Proxy pattern: Uses JavaScript's Proxy objects to intercept operations on objects. It allows for tracking changes to properties through get and set traps. This pattern is powerful for creating reactive objects but can introduce complexity due to the need for property interception.
Signal pattern: Focuses on creating reactive values (or "signals") that notify listeners when they change. This approach promotes a clear separation of concerns, making it easier to manage state and updates without intercepting every property access.
2. Performance
Proxy pattern: Can incur performance overhead due to the interception of every property access and modification. This might lead to slower updates, especially with deeply nested properties or large objects.
Signal pattern: Generally provides better performance for reactive updates. Since signals manage state changes more directly and only notify listeners of relevant changes, then can be more efficient, particularly in scenarios with frequent updates.