Coder Social home page Coder Social logo

Batch `update.send` about usestatemachine HOT 4 CLOSED

cassiozen avatar cassiozen commented on August 20, 2024
Batch `update.send`

from usestatemachine.

Comments (4)

RichieAHB avatar RichieAHB commented on August 20, 2024 1

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.

RichieAHB avatar RichieAHB commented on August 20, 2024

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.

cassiozen avatar cassiozen commented on August 20, 2024

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.

cassiozen avatar cassiozen commented on August 20, 2024

Not fixing because this will work out-of-the-box with React 18.

from usestatemachine.

Related Issues (20)

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.