110 points · by jeswin · 5y ago · 119 comments
The point of React is not the JSX, but rather the unidirectional data flow and automatic re-renders due to prop changes -- essentially modelling your application as a "state machine" and eschewing the need for a "view model" or manual synchronization of DOM state to application state.
With the "rerender" function I fear any nontrivial application will devolve back into the tangled web of event listeners we left behind when moving to React.
Personally - I think a library like this is only useful for a very narrow audience: people with an affinity for JSX that are only building webpages (not web "apps") with some basic progressive enhancement features that can be kept track of pretty easily.
I don't mean to be overly negative here - I just suggest that you alter the documentation to be more clear about the differences/limitations when compared to react. The existing docs/example is almost (unintentionally, I'm sure) misleading in my opinion.
Disclaimer: I'm the author of Mithril.js (A React-like framework that got mentioned in some other comments). I do think that the naive approach of eager render (a la backbone) can a bit limiting in terms of large scale applications, but I think the question of scalability is more nuanced than whether a rerender function exists.
I don't think calling a function vs not calling a function is necessarily a meaningful distinction: React's own `setState` is a form of "rerender" function.
The "devil in the details" comes from what the semantics of re-rendering are, and how that ties to the overall philosophy of the library. In React, `setState` abstracts over batching, meaning that one can, for example, call dozens of setState hooks from an event handler and not have to worry about multiple repaints. But on the other hand, if you're sharing state between, say a list view and a counter pill in different areas of an app, that involves a bunch of extra code (be it data-down, events-up, or using Context or redux or whatever)
On the other side of the spectrum, too much implicitness isn't necessarily good either. Angular.js had some notoriously difficult to debug rendering loop issues when you used watching in certain ways alongside Angular.js' auto-render system.
In Mithril.js, the default is that event handlers do not require explicitly calling a rerender function at all in the first place, because it starts from the assumption that 99% of the time you do want to rerender when an event occurs. But Mithril.js does also offer explicit bail-out-of-auto-render, as well as immediate rerender and batch rerender functions because in some rare cases you do want to control exactly when to render (e.g. you might want to actually double paint if part of your state is computed from bounding box measurements, or you might have multiple third party integrations in different areas of an app that render after another third party async computation completes, and ALL of that needs to be batch-rendered if they fall in the same event loop cycle).
React's philosophy is very much to always think in terms of state snapshots, and the fact that its APIs are largely declarative reflect that. Mithril.js can also be used in a declarative fashion, but it's not as prescriptive. It also allows the developer to think in terms of timelines, and procedural APIs excel for that use case. Ultimately, though, good design comes down to being deliberate about what kind of semantics works well for what kind of mental model.
Think about all the ways you can trigger a re-render: either `setState`, `forceUpdate`, dispatching an event, or some other kind of update function from a state management library. It doesn't react to any kind of assignment like would happen in Vue or Svelte. They do exactly the same as your `rerender` function here, it's just nicely hidden. There will be no more of a mess of event listeners than you'd get using React.
The docs for Forgo here show a lot of direct DOM manipulation and/or direct assignment to mutable data structures, which you then have to synchronize.
I personally almost never have to think about these things when I build with React and treat everything as immutable / pure. Then things update according to reference inequality / shallow diffing of props. You can even update a prop at the top of the component tree and it won't re-render children that didn't actually change (and without you having to orchestrate that yourself).
That's true; the upside of immutability was supposed to be more efficiency when doing reconciliation. But in reality every large React app I've ever seen re-renders entire swaths of the component tree unnecessarily due to complexity - especially now with Context, nullifying that.
It seems that a whole lot of people actually prefer mutability. See the popularity of MobX, and even libraries like seamless-immutable actually have the goal of offering a mutation interface that generates immutable objects underneath. If you can have mutations and correctness, sounds like a good deal. I've been using Svelte a lot recently, and it's a breathe of fresh air to not worry about component lifecycle.
On top of that, React doesn't do inequality checks unless you explicitly use PureComponent, or wrap function components in memo(), so you need a lot of manual work to actually get that benefit. It's basically the inverse of having to call `rerender` everywhere.
The number of React apps that render super slowly, with visible delays when typing, is proof that it is easy to make very poorly performing react apps.
That's the whole point. React does this for you in the background. You don't have to think about it.
> There will be no more of a mess of event listeners than you'd get using React.
There will be more of a mess because you have to programmatically update elements.
With React, I can alter global state and every single element that uses that state gets re-rendered. That isn't possible with this framework.
const setState = (s) => { state = s; rerender() };
Real reactivity is what you get with proxies in Vue, or a smart compiler like Svelte.> I can alter global state ... that isn't possible with this framework
You'd just need to export a state object from a module, import into the components, and call rerender after any mutation. I've actually written quite a few vanilla-js apps using this structure when I don't want to bother with tooling, small pages don't need a complex reconciler.
I'm not saying this is better btw - there are ergonomic concerns and different trade-offs, but the distance from this to what React does is much, much shorter than most people think. We've just been conditioned to accept its rules as 'normal': don't declare plain variables in your functions, don't mutate properties, don't use inline functions as props, don't rely on previous state object for updates, and so on... step outside the box and you'll get a mess too. This library is just a smaller, different shape box.
Now the optimization I haven't done is deciding whether a child needs to re-render when a parent re-renders. Comparing the props seems like a straightforward way to do this, so I'll probably spend some time over it today and implement it soon.
In theory, that sounds terrible; I don't want to keep track of when my app needs to rerender, or worry about a stale DOM because I forgot to rerender after some event.
In practice, it's a breath of fresh air compared to my work with React/Vue/Svelte. Everything is just so simple; I can use vanilla JS data structures and code organization patterns. I can architect my frontend state and logic in the way that makes the most sense for my domain, instead of ceding control flow to a heavy, footgun-y, limited-expressivity framework that demands to know everything my app does so it can decide on its own when to rerender.
I'm tired of debugging confusing bugs because React hooks mix asynchronous control flow inside the render loop and my app has to have correct rendering and logic for every intermediate state of a chained sequence of useCallback/setState hooks. Tired of telling my team we have to put off a feature because it'll take a week to do something that feels like a 3-hour task because refactoring around a framework's control structures is harder than refactoring ordinary JS features. Tired of magic reactive compilers that create buggy renders and template languages that are only nice to work with if you use the One True Blessed VS Code Plugin, and tired of frameworks that need CLI scaffolding tools because they're more complicated than anyone wants to initialize with a blank editor.
Crank.js, Mithril, and (at a preliminary glance) Forgo are very compelling to me. They offer the declarative, self-contained nature of components that I love from React/Vue/Svelte and the type safety of TypeScript for view code instead of template strings. My whole project scaffolding is just installing esbuild and generating a tsconfig.json. Maybe toss in browser-sync and watchexec if I'm feeling fancy. I don't need to make major architectural decisions based on the preferred state management tool, because these frameworks couldn't care less about how state is managed. And if I really want automatic rerenders, it's 10 LOC to write a reusable ES6 Proxy that returns an object I can dump state values into that will auto refresh if I reassign a property.
And these frameworks still feel like a state machine in the same way React does - view code is declaratively rendered from application state. There is synchronization of state to DOM, but only in the sense that you have to explicitly invoke the declarative engine, and not in the sense that you have to manually synchronize like you would using jQuery to find and change DOM nodes.
Keeping up with manual refreshes feels so simple and easy compared to all the hoops I've jumped though with the household name frameworks.
It's as the number of developers grow on projects that these things become nightmares. Having worked somewhere that used React and had extremely strict eslint and typescript settings, it was all so uniform (those type checking static linting really keep the guard rails on code quality) because you were guided to use the same effective patterns in solving those problems. In fact, all the interesting work started happening outside interactions with the framework (and more around redux, in this case) so we were more focused on business logic and other concerns, react fell straight into the background. There were only ~25 developers or so. The ecosystem and the framework really lent itself hand in hand. That shouldn't be left out of discussions like this.
I can see this model falling flat on its face after about 6 developers working in this system, especially since there is no adjacent tooling that specifically made to keep the guard rails on code quality.
I'd love to hear a counter example to that.
Edit: my point is, in order for something to be an acceptable alternative to React, it needs to have the ability to thrive in an example like I gave. React isn't for the 1 man shop, per se, or even perhaps a team of 5-6 developers that can coordinate well. Its real strength is in large application development, with `n` number of developers, where n is greater than 6. Thats just been my experience.
My projects can usually count all of the developers on one hand, often with fingers to spare. I get put on a rapid-file bevy of small projects rather than a single long-term project that grows into a large team. Time-to-MVP and rapid iterative redesign as the problem domain gets mapped out are the priorities in my projects, and light, non-prescriptive frontend frameworks work well for that in my experience.
I think it makes a lot of sense to define different best practices for one-pizza projects than projects where 25 developers can be described as "only 25". There are a ton of developers at both ends of that spectrum, enough that I wish the broader web developer ecosystem would embrace that distinction.
IMHO, a lot of Mithril code looks like React code. Things like eslint/tsconfig can be setup equally strictly regardless.
Having seen some truly gargatuan React apps, I'd actually argue that neither React nor Mithril do much to enforce structure aside from the componentization aspect (which, to be fair, is a big part of it).
Ember, for example, is arguably far more prescriptive with regards to code structure consistency.
What I do think is true of React and similar libraries/frameworks (think mithril, but also vue, svelte, etc) is that once you setup a structure of your liking, the path of least resistance tends to also be the happy path, i.e. even "copy-paste" programming generally ends up resulting in always making reasonably sized components, always using the state management mechanism idiomatically, etc.
Speaking to your specific examples: I do agree that some of the new React hooks (especially useEffect) seem to promote an ... idealistic idea of how your component should trigger and react to side effects (especially if you enable the eslint plugins) - namely always due to changes in reference equality. If you need to deal with other things (like an ID changing in a nested object that gets recreated on each render) it can be a big headache and error-prone.
On the other hand - most of these hooks (and libraries and build tools you are alluding to) are easy to modify or use something else if you don't like them. Personally I find that much easier than building web apps like I used to pre-React and dealing with manual state synchronization. But to each their own! I've seen some pretty clean non-React codebases and I've seen some pretty messy React ones, just as I have on the flip side.
The biggest red flag I noticed was the use of the "rerender" function. It reminds me a bit of writing code in jQuery and manually having to keep track of when the DOM needs updating. Obviously not a huge burden for something small but would be very interested in how it effected larger apps. Seems like a big tradeoff to have to take on that responsibility again.
Saying that, the general API of the library is easy to understand and I could imagine being productive with it very quickly.
I totally expected rerender to be a bit controversial. But if you look at React, the user does provide (strong) hints in the form of the setState() invocation - which could be done here as well.
But then again, it's a tradeoff. Simplicity, and Python's Explicit is better than implicit.
But there is one idea from React which made a ton of sense; from the time I started using it nearly seven years back. That's JSX - instead of shoehorning expressions into markup, move markup into the programming language. Forgo embraces JSX and skips most of the other ideas in React in favor of a more plain vanilla approach.
What should a developer do that needs to share state across a Forgo app?
It would be awesome if browsers just had a real template language like JSX, we'd see more "web components" which are just a little bit of JSX/or whatever templates and some DOM APIs. Developers are tired of managing binding and unbinding events. React does that well. I assume Fargo does too.
So putting aside the redux/flux paradigm, what else is the real hurdle being solved?
We already have many facilities in JS to handle state. Singleton patterns, closures etc. The example on the website uses closures to handle component state - which is simpler than React's hooks based approach.
function SimpleTimer() {
let seconds = 0; // Just a plain variable
return {
render(props, args) {
setTimeout(() => {
seconds++;
rerender(args.element); // rerender!
}, 1000);
return <div>{seconds} secs have elapsed...</div>;
},
};
}
> I don't consider reducers, actions, redux/flux to be React specificThey didn't emerge from React - but it isn't possible to do React without them. When I conduct trainings, I often see some of my students go - wow, why would you do that? So Forgo basically is an exploration of how to simplify things - and to let users pick their desired level of complexity.
Maybe you mean it's not realistic to write React "beyond toy examples" or "in the real world" without Redux, but still, I'd beg to differ there. You can get very far with plain React and the context API and other libraries. Redux definitely isn't required.
Forgo does look cool though! I like the idea of using plain variables for state, and returning an object allows you to add other things to that object (didMount, didUpdate, unmount etc).
It is 100% possible to build large React apps without redux/flux. There are entire ecosystems built around, say Mobx, among many other libraries and tools which don't even follow the flux style patterns.
> The example on the website uses closures to handle component state
I'm not asking about component state; I'm asking how do multiple components access app-wide state. I can't use a singleton for that; how do I know when that singleton is updated? I guess I could use a proxy but I don't want to do that.
> and to let users pick their desired level of complexity.
React is the view layer. It doesn't enforce any type of data layer or state management layer.
Here is a React/WebGL game I made which tracks a lot of variables and state, but does not use redux/flux...because it's 100% possible to make even make a 3D game with React without them!!!
This looks a lot like closure components from Mithril.js[0], which have been around for several years. It's nice to see people independently come to the conclusion that this approach is simpler :)
[0] https://mithril.js.org/components.html#closure-component-sta...
I've created many React apps without any complex state management libraries :-)
It's plain JS with a very similar DX to JSX, and I think addresses that really well.
My team also works closely with Chrome, Safari, and Firefox on proposals like Template Instantiation that aim to build up more APIs that template libraries can use to be smaller, faster, and more interoperable.
I really think we will eventually get good templating in the DOM so at least the most common use-cases are taken care of.
HTML imports were supposed to be the holy grail to solve this, but nobody but Chrome supported it :(
- return values are a data structure, so they’re render-target/render-implementation agnostic
- it’s compile time only/effectively a macro, so the compiler can choose how to render subtrees
I love the “it’s actually part of the language not a build tool” part of lit, but it can’t satisfy those other goals without giving up its core selling points.
const [v, setV] = useState(123);
First call v gets set to 123, second call it doesn't. WAT!Algebraic Effects are the thing I'm most glad React introduced, hooks are nothing short of a revolution for UI.
Everything that IS actually just JS is listed (hooks, actions, reducers), but the only thing that isnt (JSX) is used without a question.
Sometimes React critique just reads like an elaborate trolling attempt.
“It’s just JS” can certainly do that but you need additional compile time signals.
We've been trying to remove view from logic since the 90s, and move towards declarative views with data binding. Keep your nook and crannies away from the presentation layer.
But all the industry wants is shoving PHP in the browser.
I think it's sad. We're making the UI layer always more complicated.
Let's say your UI changes, like a redesign... you can rewrite your component and probably need to change most of them.
If your UI was just dumb and declarative and the data was salt on top, changing the UI is trivial.
The UI should declare what the UI should look like, not describe how it should do it.
This is why, as an old timer, I much prefer the direction VueJS took.
Edit: great lib though, anything small is a win.
The JS has to grab DOM nodes by class or ID and is highly coupled to its structure anyway, so putting them together (as React does) seems far more logical in my opinion. Separating them into files and using string classes to look them up is far less easier to read and leads to runtime issues (since a typo isn't actually a code error but just silently doesn't work).
JSX is really not like PHP at all. PHP just writes out strings - JSX is all JavaScript objects. What you are describing is more akin to something like Handlebars or Angular templates. Plus, JSX is just sugar and is not required to use React if you prefer something like hyperscript (no compile step needed in that case).
My point mostly was: separate view from logic. Intertwining them only makes maintainability and cognitive juggling worse.
This is exactly what React does especially for stateless components that purely consume data. The component declartively says this is the data I need. The component doesn't care how that data is retrieved, that's an implementation detail separate from React.
For stateful components, this is also achievable but requires a little engineering and some good architecture (this is IMO the hardest part of 'React' - and this isn't even a concern of React - since React doesn't prescribe any specific approach).
If you define all the functionality for a component well, you should be able to easily rewrite just the view (the return value of a fucntional component or of the render method for class components) without changing any of the existing functionality.
This can be done by defining your component's behaviors via hooks (custom or builtin). Those hooks should provide any functionality and data your view needs and exposes that to the component. If no new data or functionality is needed, then nothing in these hooks (and more broadly code external to the render/return value) changes.
All that changes is the return value of your component and any css you want.
If you change the view, yeah you might have to update some event handlers for buttons that are now inputs, but that's not a UI only change, thats changing functionality too.
The worst PHP code I’ve seen is the kind that mixed database queries with presentation, and that was just bonkers. Just a really truly awful mess.
For me, that was the “PHP” I envisioned and what I didn’t want to rehash with React, and I can confidently say that has worked out pretty well.
I prefer the template syntax of .vue files or similar to the one riot.js uses. They use basically the same syntax html uses, just on a smaller scale and limited to a single component. That way you don't have to invent new was of embedding markup in code.
A 4k hobby project is not a React alternative. It's a view rendering library.
It's a view rendering library, but it also does state management while not actually doing it. Forgo just makes some design decisions that makes state management not require any code in the library.
So, it does what the react and react-dom packages do - it's not just the view.
Very similar to how Mithril and Imba solve state management: just use vanilla objects/primitives.
import React, { Component } from 'react'
class ManualStateComponent extends Component {
state = {
now: null
}
constructor(props) {
super(props)
}
// Since you don't want to call `setState`, here is a method with the name you prefer
rerender() {
this.setState({
now: Date.now()
})
}
}
// Example Component
class SimpleTimer extends ManualStateComponent {
constructor(props) {
super(props)
this.seconds = 0 // Just a plain variable
}
componentDidMount() {
setTimeout(() => {
this.seconds++;
this.rerender() // rerender!
}, 1000)
}
render() {
return <div>{this.seconds} secs have elapsed...</div>;
}
}
gist: https://gist.github.com/chrisabrams/9e140d212098033365a76666... <script>
let seconds = 0;
setInterval(() => {
seconds++;
}, 1000);
</script>
<div>{seconds} secs have elapsed...</div>
Note that this deliberately functions slightly differently: it uses setInterval rather than repeated setTimeouts. This makes a much more accurate seconds counter, as setTimeout will wait for at least 1000 milliseconds before incrementing seconds and setting another timeout, meaning that you will always count time too slowly, commonly around 1% too slow, but more at times like if JavaScript execution is being throttled because the page is in the background. If you really wanted to do it the other way, it’d be something like this: <script>
let seconds = 0;
function increment() {
seconds++;
setTimeout(increment, 1000);
}
setTimeout(increment, 1000);
</script>
<div>{seconds} secs have elapsed...</div>I'm aware some of the React community use hooks, some of us still use classes. Classes provide a better interface when dealing with state that is shared between parent and child. This is a write up much better than I can explain: https://react-redux.js.org/api/hooks#stale-props-and-zombie-...
Side note: Is it just me, or is there a new "NKB alternative to X.js" everyday?
Reactor - exactly 0kb (zero) ReactJS alternative built-in into Sciter.JS :)
This https://github.com/c-smile/sciter-js-sdk/blob/main/samples.s... works in Sciter.JS as it is - without any external frameworks.
`JSX` and `element.patch(jsx)` are built-in into Sciter.JS. And it uses ES2020 so no Babel step is required.
Which actually makes it even more amazing, but that explains the 0KB for those who don't recongize the framework by its name :D
Everyone should check out sciter for their next project if you're considering something like Electron, though!
- Forgo Router https://github.com/forgojs/forgo-router
- Error boundaries for sub-component error handling
- CodeSandbox Links https://forgojs.org/#try-it-out-on-codesandbox
https://news.ycombinator.com/item?id=25677272
It seems like lightweight web frameworks are the "Hello World!" of Show HN.
I recommend developers to look into history of React, why they chose to build it in first place and search for youtube videos explaining React concepts.
https://reactjs.org/blog/2013/06/05/why-react.html
React is about data flows and managing state transitions with user experience.
Lot of these React replacement projects simply try to reinvent the wheel.
Reminds me of all the jQuery replacements that were attempted, but quickly realized that in order to support basic features, they had to recreate jQuery.
Often a new thing, like react, has a very epic core idea, but the implementation leaks through, and/or it is interlaced with other ideas and concepts.
Projects like this are about replicating a core concept or an idea without the other stuff around it.
I don't have a good description for it yet, but I feel like I have seen this a couple of times now: a new i.e. product/tech/library comes out with one ore more interesting new concepts, and afterwards, over time, these core concepts get unbundled and isolated. From there, you can remix it with other ideas.
It's like the first wheel came on a car, then someone took the wheels off and played with them to invent the motorcycle.
Also that maybe was the shittiest made up example in history, but I hope you get the idea.