cassiozen / useStateMachine

The <1 kb state machine hook for React
MIT License
2.38k stars 47 forks source link

Batch `update.send` #38

Closed cassiozen closed 3 years ago

cassiozen commented 3 years ago

Calls to update and send may happen outside of a user interaction, React won’t batch the state updates.

RichieAHB commented 3 years ago

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!

cassiozen commented 3 years ago

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

RichieAHB commented 3 years ago

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!

cassiozen commented 3 years ago

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