r/reactjs • • 7d ago

Show /r/reactjs Treflex demo – live hot-swap between React and Solid

https://youtu.be/vCTUfypEsi8

Live swap demo: https://tgoh.github.io/treflex/swap/

Treflex is something I've been working on for the past few years: a headless state engine. Your app's logic (state, async work, timers, connections) runs on its own, and React or Solid is just a view you plug into it. In the demo you can swap between them while everything's running, and the app doesn't notice.

Why: AI agents write a lot of front-end code now, and async is where they slip: races, double starts, work that dies on unmount. With the logic out of components, those mistakes get caught. It's tested without rendering, a test controls the order async calls answer in, and the runtime and lint rules fail with errors that say what to change.

const FishReceiver = receiver<IFish>("FishReceiver")({
  *"Fish/Swim"(fish) {
    fish.X = (yield* random()) * 100;
    fish.Y = (yield* random()) * 100;
  }
});

function* addFish(school: ISchool) {
  const fish = yield* entity(newFish());
  school.Fish.push(fish);

  // The timer belongs to the fish, not a component
  yield* startTimer(fish, "Fish/Swim", FishReceiver, 3000);
}

function* releaseSchool(tank: IAquarium, schoolId: string) {
  // Every fish in the school stops swimming. No cleanup needed.
  tank.Schools = tank.Schools.filter((s) => s.$Id !== schoolId);
}

It's 0.2 and still changing. Questions and feedback would be greatly appreciated.

0 Upvotes

24 comments sorted by

8

u/Honey-Entire 7d ago

So you reinvented RxJS / Redux Saga because AI made it easy instead of just using an existing library? Do you even know why this type of programming fell out of favor in web development?

2

u/musHeaer 7d ago

tbh people forgot how miserable debugging long chains of generators actually gets once the codebase grows.

-3

u/Tsya 7d ago

A lot of what made debugging sagas difficult wasn't the generators, it was how they were composed. Sagas were started by watchers listening for action types, and they talked to each other by dispatching more actions, so any one event could set off a chain of sagas across the app with nothing in the code linking them together.

In Treflex your entry point is the entity, so it's much closer to calling a method on an object directly. You can follow it from start to finish in your editor.

Treflex also locks entities by default, and you specify the points where other actions can interleave. That eliminates the majority of race condition bugs, because they simply can't happen. Actions can also be tested by feeding in events in whatever order you want. That allows you to simulate any potential race condition deterministically.

The other part about debugging was tracking state. With Treflex everything is stored as state. That not only gives it the ability to snapshot and reload, but it also means you don't need to step through generators to work out where things are, or how the state is changing.

If you give it a go, I think you'll find both debugging and testing in Treflex much easier than in sagas.

0

u/azangru 7d ago

So you reinvented RxJS / Redux Saga

Which part of OPs api reminds you of rxjs?

3

u/Honey-Entire 7d ago

Both provide:

  • Tracking and management of concurrent events

    • switchMap (RxJs) vs latest (Treflex)
    • exhaustMap (RxJS) vs leading (Treflex)
    • forkJoin or combineLatest (RxJS) vs parallel or parallelSettled (Treflex)
  • Lifecycle management with the ability setup or teardown a "subscription" (RxJS) or "entity" (Treflex)
  • Support for single, recurring, and streamed event sources, catchError in RxJS and onError in Treflex
  • Error routing & recover
  • Memoization of derived state

They differ where:

  • RxJS uses a pipeline-style flow for chaining events and is highly composable
  • Treflex anchors actions to single entities
  • RxJS lets you bring your own state giving you the freedom to track state however you need it
  • Treflex keeps its own state

The overlap between the two is significant and comes across to me as a difference in naming conventions vs a novel, genuinely new solution. In the vast majority of applications, neither is worth the added complexity or mental model required to scale a maintainable codebase.

-1

u/Tsya 7d ago

You're right that there are some overlaps in the API, but that's because it represents things that any framework needs.

Under the hood they're completely different, and the difference is what allows Treflex to do things like automated cancelling, per entity locking, snapshotting and reloading, etc. The fact that the entities are the root, and actions/subscriptions/timers are all tied to those, is what makes Treflex unique.

You don't get those from RxJS without wiring them up yourself, and that's why its mental model is much more complex. As I said before, your state and your streams are two separate things you have to keep in sync by hand.

-4

u/Tsya 7d ago

I do actually. The main issue with redux saga was the redux part. Having a tree for the state I still think is a great idea, but the main issue was everything else around it.

Composition was difficult. Cross-cutting concerns were difficult. There was a large amount of boilerplate required to make immutable reducers and hook them up.

Treflex was designed to work around all of those problems.

Because actions act directly on entities you don't have the issue with composition. You can create SPA's with dynamically linked modules at runtime with no problems.

Cross cutting concerns are solved with the Messaging system. Each entity in the tree can publish messages without needing to know about the subscribers at the end. You can see this in the demo, there's a voucher in one of the chat messages that applies to the trips.

Additionally Treflex ties all of it's living actions/subscriptions/timers to entities, something that typically had to be done by hand. That's why when you remove the fish they automatically take all of their timers with them.

I think if you give it a shot, (or if you throw an AI agent at it), you'll see that there's a lot of benefits to this type of paradigm.

5

u/Honey-Entire 7d ago

The problem with redux saga was never redux, the problem was saga and how side effects are nearly impossible to keep a handle on in large UI systems. Messaging models are rarely the right choice for UIs where most of the time the UI is static and unchanging

The one exception to this I can think of is live dashboards with streaming data. But I still wouldn’t use an RxJS OR saga-based solution for it, let alone an AI generated one with no track record…

-1

u/Tsya 7d ago

I think you have two different points there. I agree with your point about static UIs; for the most part, frameworks are pretty overkill for anything that doesn't move.

However, I think you'd be pleasantly surprised by how Treflex handles both side effects and concurrency.

The issue you're talking about with sagas and RxJS epics is that they created layers on top of the state tree that you had to manage by hand. Because sagas essentially lived forever, you had to manually track their life and death cycles, and forgetting to clean any of those up led to the spaghetti you're talking about.

In Treflex all work is bound to an entity. Take the fish, for example. You can spin up any number of actions on them (like swimming in the demo), and they all get cleaned up automatically when the fish leaves the tree.

The problem with the old method is that state and sagas were two separate things you had to keep in sync. In Treflex you deal with entities. It's much closer to something like OOP, but where an object's running work goes with it when it's removed.

Concurrency is something Treflex also deals with well. An action holds its entity across every async point by default, so nothing else can interleave, and you can open any specific wait to let other actions in. You control exactly when interleaving happens. I'd be happy to explain more if you're interested.

3

u/rydencode 7d ago

lol you really posted an ai slop comment?

1

u/Tsya 7d ago

I’m pretty sure AI would come up with something a bit less rambling than my reply lol. But if you had any actual questions I’d be happy to answer them.

2

u/TheRealSeeThruHead 6d ago

I mean we are beyond this already

Use fold kit or something else that is far more opinionated than solid or react.

I created a version of solid that fully integrates with effect. Stores all changes Ina log agents can query and does fully distributed tracing of every component all the from the frontend to the db.

I think we’ve blown past the agent friend state manager for react but maybe everyone needs to catch up

1

u/Tsya 6d ago edited 6d ago

Frameworks are the language of the UI. Even when you use agents, the choice you make is important. Which framework you choose will determine what is easy, what is difficult, and sometimes what is even possible.

Here's Foldkit's homepage demo, written in Treflex: https://codesandbox.io/p/devbox/rf344j?file=%2Fsrc%2Fcounter.ts

There's two important things to notice.

Firstly the code is much shorter, while still being type-safe for agents.

Secondly, Treflex is specifically built to handle interleaving events. By default an action holds its entity, so nothing can interleave with it. If you check out the commented line, you'll see it's a simple wrapper that marks a wait as "open". That marks exactly where other events can get in, so an agent knows to check the state again after that point.

Foldkit is based on Elm, so every message can interleave at any point. The demo only avoids it by disabling the buttons. If anything else sends that message, like a keyboard shortcut, a subscription or another view, the guard isn't there. That's the type of bug agents are likely to miss, and it shows up in prod. In Treflex you get that safety for free.

There's also a test in counter.test.ts that sends "Add 1" during the reset and checks it's held until the reset lands. The fact that you can test this type of race condition stuff is what makes it better for agents to work with.

1

u/TheRealSeeThruHead 6d ago

My store can be a state machine that just doesn’t accept an add 1 action while it’s resetting. Which can be fully typed and modeled and does what your thing does generically I think.

2

u/Tsya 6d ago

I'd love to see it if you have it available? The only reason I wrote this is because I couldn't think of a simpler way of doing it. Are you using XState behind the scenes?

1

u/TheRealSeeThruHead 6d ago

It’s not public right now, it’s in active development

I’m working on dev tools and ssr and t all that

1

u/Tsya 6d ago

Ask your agent to compare it to Treflex? See what it thinks, only takes a single prompt.

1

u/TheRealSeeThruHead 5d ago

1

u/Tsya 5d ago

Your method puts the lock in the store, which is definitely a step up over Foldkit's example. But it still has its own downsides.

Because the reset is split across two commands, everything can interleave between them. The phase flag is basically a hand-rolled lock, and nothing forces anyone to check it. Your own Reset and FinishReset don't, so a second Reset starts it again and a stray FinishReset ends it early. If the example missed it, agents will too. In Treflex the wait is inside the action, so nothing interleaves unless you mark that wait as open.

1

u/TheRealSeeThruHead 5d ago

That’s just a store based on alchemy domains

You could make a store based on xstate, state machine capabilities based api

Honestly not sure how much I care about it. But it’s solo merging I’ve been thinking about.

I’d that that over your locks tho

1

u/Tsya 5d ago

XState has its own tradeoffs. It's great for a single flow, but it gets awkward once you need lots of parts talking to each other. If all you need is one piece of functionality, it works fine. Treflex was designed from the ground up for large systems with many parts that talk to each other.

Treflex's messaging system lets individual systems talk to each other while staying decoupled, and they still keep all the locking protections.

Happy to spin up another example if you’d like to see it.

1

u/Tsya 6d ago

Actually you make a good point. Why don't you throw your agent at Treflex and see what it thinks?

1

u/Jazzlike-Web-3695 7d ago

how does state survive the swap? like if a fish is mid-animation when you switch to solid, does it continue from the same position or restart

1

u/Tsya 7d ago

It continues from where it was. The fish entity stores where the current swim started (FromX/FromY), where it's heading (X/Y) and when it set off (SwamAt). The glide itself is just a CSS transition, so when the new renderer mounts it works out how far into the swim the fish is and starts the transition partway through. The swim timer lives on the fish, not in a component, so the next swim fires on schedule whichever renderer is showing it.

Same thing happens on a page reload, since all of that is in the saved state.

The tail wiggle restarts, though, since that's a pure CSS loop with nothing in state.

You can try all of that in the live demo to see it in action yourself :)