Comments (4)
Oh wow, I didn’t realise that this was planned in React 18. That would be by far the best solution. Nevertheless, I still enjoyed thinking about this problem 😬 - thanks for sharing!
from usestatemachine.
I had a think about this and the only way I can see it being done is waiting for the call stack to empty before firing all updates that happened in that tick of the event loop.
The naive solution here would to be wrap the call of effect
in React.unstable_batchedUpdates
but obviously this wouldn't batch any updates that happened asynchronously.
The method outlined below would potentially require giving up some things in terms of synchronous expectations, but I'm not sure if that's a problem.
Example implementation
/**
* Pseudo implementation
*/
const batched = [];
// Placeholder for proper React method
const React = {
unstable_batchedUpdates: (fn) => {
console.log("- batch start -");
fn();
console.log("- batch end -");
},
};
// This call does most of this work putting thunks on a queue and flush after
// the stack is empty
function batch(thunk) {
if (!batched.length) {
Promise.resolve().then(() => {
React.unstable_batchedUpdates(() => {
batched.forEach((fn) => fn());
});
batched.length = 0; // deletes array element
});
}
batched.push(thunk);
}
// Simplified drop in for state machine (I wanted to prove this concept to
// myself before digging into the code). Provides an `update.send` API that uses
// the batching above. To be passed to an exaple effect and holds context
function createUpdater(init) {
let ctx = { ...init };
return (ufn) => {
batch(() => {
ctx = ufn(ctx);
console.log("Do update -", ctx);
});
return {
send: (event) => {
batch(() => console.log("Do send -", event));
},
};
};
}
/**
* Examples
*/
// Run these inside promise ticks to keep the output neatly ordered
Promise.resolve()
.then(() => {
console.log("\n--- Sync Example ---");
// Example effect that calls both update and send in the same tick of the event loop
const syncEffect = (update) => {
update(({ count }) => ({ count: count + 1 })).send("Sync event 1");
update(({ count }) => ({ count: count + 1 })).send("Sync event 2");
console.log("Log sync");
};
const updater = createUpdater({ count: 0 });
syncEffect(updater);
})
.then(() => {
console.log("\n--- Async Example ---");
// Example effect that calls update and send in different ticks of the event loop
const asyncEffect = (update) => {
update(({ count }) => ({ count: count + 1 })).send("Sync event");
Promise.resolve().then(() => {
update(({ count }) => ({ count: count + 1 })).send("Async event");
});
console.log("Log sync");
};
const updater = createUpdater({ count: 0 });
asyncEffect(updater);
});
The log from above is as follow:
--- Sync Example ---
Log sync
- batch start -
Do update - { count: 1 }
Do send - Sync event 1
Do update - { count: 2 }
Do send - Sync event 2
- batch end -
--- Async Example ---
Log sync
- batch start -
Do update - { count: 1 }
Do send - Sync event
- batch end -
- batch start -
Do update - { count: 2 }
Do send - Async event
- batch end -
Considerations
As alluded to above, I'm not sure how delaying updates will effect any existing assumptions about context but my feeling is that I don't think it should have any major impact (and this definitely falls inline with React's own model of state anyway).
There may also be a simpler way to do this (e.g. as mentioned elsewhere, other APIs help this but don’t completely eliminate this) but I thought I'd put this up as a straw man to drive the discussion based on the API as it exists today. Feel free to ignore or dismiss, I know comments in open-source repos like this take a lot of time to course-correct if they're wildly off the mark!
from usestatemachine.
That's an amazing write-up, @RichieAHB! Thanks a lot.
I was playing around with React's 18 automatic batching and it looks like it just works out-of-the box for useStateMachine
, so maybe we don't need to do anything here.
Link to codesandbox: https://codesandbox.io/s/sad-dream-9ch3b?file=/src/index.js
from usestatemachine.
Not fixing because this will work out-of-the-box with React 18.
from usestatemachine.
Related Issues (20)
- Suggestion: mayTransition function to check if a `send()` would pass guards. HOT 6
- Suggestion: Have an explicit initial event? HOT 1
- Types Roadmap HOT 26
- `nextEvents.includes` inferred to `never` HOT 9
- DX for typed events HOT 7
- "$$initial" event discussion. HOT 11
- Document the difference between nextEvents & nextEventsT HOT 1
- Update references to init event on state
- Documentation discussion HOT 9
- Prevent memory leaks HOT 3
- Disallow extra events in schema
- How to use external machine config with correct type (using TypeScript)? HOT 8
- Make "creating" and "using" a machine seperate HOT 5
- Migrate away form TSDX
- useMachine return undefined in production environment HOT 5
- [Question] How to update context without changing state? HOT 1
- How to expose send func with useImperativeHandle?
- Async Guard functions?
- How to get the type for state and send?
- Issues with Typescript v5.4 HOT 1
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
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.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from usestatemachine.