242 points · by vinnyglennon · 3y ago · 313 comments
I can crank out tools in minutes. No complicated build systems or web pack or dependency management system. No react, no reduce, no apollo or graphql. No typescript, etc.
Just simple go, html, css, and a bit of javascript when it's needed for a form. I don't minimize anything, or try to do anything fancy. It faster to develop in, and faster to load in the browser.
I'm specifically talking about internal tools here.
That’s great for you if your home is close enough, then of course you should have been walking. But it’s not exactly generally applicable advice.
The whole point of React is to create interactive UIs, that’s why it’s called “react”. And you can’t do that with a templating system.
Much simpler tools can work if you allow for less fluid interfaces, and this may be a non-issues for a tool running on a LAN.
We're never replacing our old-style PHP internal tools, because according to business users it's "instantaneous", and any attempts to use a more SPA approach cause complaints about "sluggishness".
15 year old software product built on Perl CGI with a server rendered html+jQuery front end. Massively grown past the point where that is suitable, with plans to add interactive features that would be crazy to do with the old architecture. Have moved the whole thing to a VueJS frontend. We have kept the old Perl CGI server architecture, just refactored it to return JSON.
You are complete right, to many people chose a tool based on fashion. There are two main things to consider when picking a toolkit or architecture for a web app/site:
- what do my team and myself know well, what will be the most efficient?
- where is the state? Is it predominantly in a database on the server or client side in the browser?
The project I'm on when they first asked those questions, the answer was, Perl CGI and server side state in a database. That is no longer the case for the second question, the state is increasing moving to the client side, and that's why I joined the team.
If I was answering the second question as server side right now I would probably pick htmx+alpinejs.
However, sometimes the first question overrules the second.
(There is a third question, do you need an installable app too? In which case a SPA with a toolkit that supports PWAs or web view wrappers is a good option if you want to only have a single codebase)
I love statements like this. It's as if things are just complicated for the fun of it, not because they need to be/they solve complex problems.
99% of us live in a world that does not need reactivity, yet so many of us are led to believe that we are in a world that does. All because Facebook made React (for what original use case? Facebook Ads Manager?) doesn't mean we're all going to be Facebook, need to be Facebook, or want to be Facebook.
When I need the reactivity, I need to sprinkle it on; I don't need to use reactivity when it's not needed just for the few cases that do.
I mean if your tools are that simple, this is a no-brainer. The problem is when you have to scale up. Internal tools can get complicated because their user base is often highly specialized technical users. Managing reusable components, behavior, and state of a complex application is when you need something like React.
That said, I'm liking Yew a lot more than React. The difficult thing with React is state management, which is why it's common to resort to immutable state (even though that's a real pain in JS), and even then React chickens out by assuming components are impure by default.
Everything makes way more sense in Rust. The big downside is that Yew doesn't really have anything like Bootstrap or Blueprint yet. I mean there are ports like Yewprint (great name) but they seem to be complicated to set up and you lose the really nice simplicity of Trunk.
Until you get told to implement more reactive features, then it's over. Using Pure JS/JQuery for reactiveness is outright horrible.
Turbolinks/hotwire? Not as easy with Go as with Ruby but can be done
The thing is maintaining simple state given the current abilities of css and JavaScript is a little bit more verbose in React than otherwise.
Back then, people fell in love with GMail and suddenly everyone thought they were building another GMail. This wasn't true. Most people were building an app with a couple of forms, a datagrid and maybe 2 highly interactive pages.
PHP, Python & Ruby frameworks gave perfect support for all this >10 years ago. You had jQuery plugins you added to page in 30 minutes and you had validation. In 2 hours you had a datagrid. Autocomplete, datepicker, things like this was no problem.
It was a form of egoism all the time.
Coding Sign In page was work for less than an hour. Now, in React, it's 2 days.
Look at developers now and compare them with senior devs a decade ago. My estimate is that development today is 4 times slower. Given a growth of salary at least 50%, a system back then in MySQL, jQuery, Django or Zend Framework for $40,000 is now $240,000 in React with GraphQL, Mongo, etc.
React generates billions of dollars every day.
If you have a basic project the tools should be basic.
There are times where React/Vue/SPAs are warranted. It's not 100% of the time, however.
Small "unless" and you are forced to make all your APIs generic because there might be many clients. Small "unless" and you'll ignore all power features of your database and dumb-down your approach to data because user might want to switch a database. Small "unless" and you will make your app ultrascalable even when you have no proof there'll ever be more than 100 users.
This is a disease that makes development slower and more expensive even when 95% of time, the customer needed something fast and cheap. No, most devs aren't building another GMail, most devs are building something that could have been modelled in 2 weeks in Visual FoxPro 25 years ago.
I have seen it. It is all "But React has this built in!" and "React does this nicely!" until it comes to actually implementing components. Without a need for interactive widgets to avoid page reloads and avoiding becoming a non-SPA again, it will take a lot more time to get things done with React, that it would take to simply churn out server-side rendered templates the traditional way. UIs that could have been done in 2 weeks the traditional way take suddenly multiple frontend devs a few months, with things like the back button not working correctly.
With anything more than html, css the complexity is not worth the return.
We've done away with everything that needs internet to build or deploy (npm, dockerhub, brew, whatever). Primarily for the security theatre around package updates.
So much simpler now. Backend is very well integrated with the entire ecosystem. Exact same setup as production. Folks who build internal admin tools tend to (and they should) know that part much better.
Everything is instantaneous.
We avoided all frontend libs. Some (like moment.js) needed extra work on the API side, but that took an hour at best to find an existing backend method to use.
All of the admin UI stuff is like < 100 kb. In 1 repo. Everything works without javascript, in all browsers (including lynx).
Night and day contrast against all previous versions where we used a mix of jquery, then angular and finally react with all their baggage and unexplainable dependencies to utter dismay.
Clearly the case of using the wrong tools but good lord did it take a while to get rid of the FUD around html only tools.
Some things need fancy react GUIs. Others need to surface business data to a small number of people in a simple and cost-effective way.
I also wrote a < 0.5Kb DOM abstraction that basically just saves a bunch of typing (get element, replace element with something, go fetch some shit off the server, add style, remove style) and that covers about 90% of the "would be nice if it did this" use cases.
This all gets compiled into one binary file, resources as well, chucked in a docker container and pushed to Kubernetes.
I would've switched to Astro for that use case, mainly because you could still leverage your understanding of React/Vue/Svelte/whatever within those mostly static pages very easily, plus the markdown support is brilliant for internal tooling.
The truth is solution is in the middle. Hotwire/Liveview type.
This way you can have the performance and simplicity of Go with the reactivity of SPA and the SEO should you need it, I know, internal tools.
The only package to my knowledge in Go doing this is "Kyoto" but it's far far away from being proper or in a easily usable state.
If anyone knows any other Go packages that do hot/liveview please, I'm all ears.
And don’t be afraid to use this approach outside internal tools.
fewer conditions now than it used to be, but you still need to do this at times.
Usually I take it as a sign I should move to using a store.
Sveltekit is very good.
Now, the reactive blocks, where an update to _any_ variable used in them trigger the re-evaluation seemed rife for abuse - particularly when the variables could be brought in from other files, but I forget the mechanics behind that.
I used it plenty of course. Forgot how it worked the day after I stopped working on the project though.
For example, this file https://github.com/sk0g/peripheral-emulator-web-app/blob/mas...
Edit: unless you mean lines like `ultrasonicDetectedDistance.update(v => v = distance)`, which yeah was an interesting quirk. Not enough of a pain to go with something like React, thought that wouldn't meet the latency requirements for this project. TBF neither did Svelte entirely, but it got close.
So you basically stopped being a fullstack dev, and moved to the back-end.
Sit down and carefully consider what is the difference between front-end and back-end development, and why that distinction exists in the first place.
If your output is HTML and CSS, you are full-stack dev. There are frontend-heavy full-stack devs ignoring backend with Firebase instead of proper backend. Nobody is telling them they aren't full-stack. So let's stop calling developers backend when they provide backend-heavy solution with a bunch of jQuery plugins or HTMX app.
All of these bring 10 benefit but add 12 problems back. It makes developing project slow at start, slow at medium term, and super garbage at long term. If developers get paid $100k+, I think they should be able to write good codes and have a good team instead of using these to save them from mediocrity.
If you have to really do SPA, pick something that's not bloat, not slow, not flaw .. instead of "hiring pool" BS.
And as a side note: can we *please* stop shitting on every React post that appears on HN? All this hater energy is really starting to be a drag.
The most basic example is making an external request based on props: can't do that in the render loop because it has to be pure, since React may run it multiple times before committing to the DOM. `useEffect` is the only way you can get a guarantee that it will only be run once after rendering, and only when its dependencies change.
The react docs literally call it an escape hatch [0]. First sentence.
[0]https://beta.reactjs.org/learn/you-might-not-need-an-effect
useEffect let’s you safely communicate with the world outside react (ie cause side effects). It’s the only reliable way to …escape.
The original docs made no such claim.
Which brings us back to the biggest problem with useEffect. Even the react devs don’t seem to have a clue how it should actually used, until only recently, despite it being among the 2 most used hooks ever since hooks were introduced.
Ie writing reactive code but relying on the React render loop to trigger reactions. The problem is that you can no longer step through your code in full and as you say, your code now mandates flushes to the DOM that are unnecessary (mid computation).
It's better to setRows at explicit places or learn and use a library like rxjs if you really need to encapsulate that complexity.
But there is a lot of mutable code that could be immutable, and `useEffect` is how that happens in React.
Kind of ironic when this post kicked off a long argumentative thread shining a light on the exact things people don't like about React... "escape hatch", "impure side effects", "useEffect... huge point of failure... it sucks", arguments whether hooks and refs are immutable or not... and these comments are coming from people who claim to like React!
So like many other functional programming langs/libs/frameworks react had a controlled means to run side effects.
That’s the escape hatch of useEffect. It’s not a bad thing. It’s thematically same as the unsafe block in Rust. It allows you to reach out of the main paradigm, when required.
React is complex because views aren't pure; slow because it has to rerender things that didn't change, because it doesn't actually know what changed, because views are impure; hard to program because impure views create bugs that even that extra complexity can't fix; and has all those escape hatches to change execution time and memoize things because the execution time actually has semantic value.
And that's react, that incredibly well designed thing with incredibly knowledgeable authors, that made a huge effort to think about every problem.
Non-pure reactive systems just do not work.
E.g. an outspokenly pro-climate politician who passed the 'frack through orphanages with baby seals bill' will not be taken seriously because actions don't match reality.
IIRC useEffect was not originally called an escape hatch and that terminology was pegged on once they realised that a fundamental hook was actually a 30mm footgun.
To make it worse they haven't provided a clear way to deal with the problem instead relying on 3rd party packages
The beta react docs have a number of great examples of this!
cf. "can be please stop hyping .. [favoured tech of the month/year/decade]"
Talk about pissing into the wind.
[0]https://beta.reactjs.org/learn/you-might-not-need-an-effect
I think HN is averse to it because it's blamed for "how complicated the web has become". If only we would all settle for simple static websites!
One other aspect that I find important to understand about the `key` property is that it only has to be unique among its direct siblings, but it doesn’t have to be unique globally.
Giving every item a new key on every update does not help with that - in fact it is likely strictly worse than just using index since it will cause every item to re-mount every update https://beta.reactjs.org/learn/preserving-and-resetting-stat... which is unlikely to be what you want.
React can’t see the difference between a reorder and remove&insert. When reordering items the state should be moved as well; when removing and inserting a new item, state should reset.
Using an array index is equivalent to silencing the error
It depends on what your data source is. If it’s a stable sorted list that only ever gets appended at the end, you can use the index.
At the end of the day, there is no hard fast rule for the key. You have to know what your data source is.
You have to know what you’re doing.
fwiw the author specifies says not to do this. The advice is to generate a unique ID when items are created, not when they’re rendered.
FWIW, these tips are also covered in his React course and he makes it clear in the course that this key generation technique should only be done when items don't have something better to use as the key. I think the blog post is just missing that context.
Funny, but sorry state of affairs: we need a new word for cryptography [1]:: mysticography [2]? "About 1 results" in Google Search, that's a first.
[1] https://www.etymonline.com/search?q=cryptography
[2] https://en.wiktionary.org/wiki/%CE%BC%CF%85%CF%83%CF%84%CE%B...
> crypto.randomUUID is a method built into the browser (it's not a third-party package). It's available in all major browsers. It has nothing to do with cryptocurrencies
Some common warning signs are generic parameters for components and using a prop as the default value for a state hook. But neither of these are a reliable indicator of a problem.
These bugs also often lie hidden for a long time because They can be hard to trigger because you need the same structure of components with a generic property changed. But when they bite they seem like impossible errors.
I've wondered if React could add a useStateKey([deps]) hook that would allow forcing a state reset if the given values change. This would work similar to a key attribute but be controllable by the code inside the component.
That issue probably wouldn’t exist except that React has to make some concessions to performance, therefore component reuse, therefore component state working in sometimes unintuitive ways.
I agree
"Evaluating with zero" doesn't apply because you use Reagent's builtin Hiccup functionality instead of JSX and you have no temptation to use anything like these single-js-expression code patterns because, well, there's no statement/expression divide in Clojure.
"Mutating state" doesn't happen because you don't mutate things anyway.
"Not generating keys" does happen.
"Missing whitespace" does happen (I think?)
"Accessing state after changing it" - Nobody uses state hooks as it's just worse than the normal atoms way, although there's a way to do it.
"Returning multiple elements" doesn't happen since, well, you can return multiple elements, components return vectors (Hiccup is vectors based data structure).
"Flipping from uncontrolled to controlled" again is state hook specific, which are practically unused.
"Missing style brackets" is JSX specific, doesn't happen in Hiccup.
"Async effect function" doesn't happen.
(The story is mostly the same with Reagent alternatives too)
For others' context, it's something like this:
setFoo((f) => f + 1);Another post I found insightful is this one, translated from a post by the author of the Alibaba Hooks library:
https://enlear.academy/5-things-i-disagree-with-react-hooks-...
It is also quite useful to check https://ahooks.js.org/hooks/ directly: Observing that there are hooks for seemingly basic tasks, and reading their linked code, makes it easier to figure out more React anti-patterns, simply by seeing what the hooks author did instead.
I really wish the official documentation was better. Often the docs are self-referential, referring to how current approaches are better than thing X React did in the past, and then the trail gets lost, instead of explaining from first principles how things work and why they are done the current way.
Unless I'm missing something, I think the "Async effect function" solution is not correct:
React.useEffect(() => {
async function runEffect() {
// Effect logic here
}
runEffect();
return () => {
// Cleanup logic here
}
}, [userId]);
This looks like a race-condition where cleanup may be done before `runEffect` has finishes resolving, and any errors thrown in `runEffect` will be unhandled promise rejections.Specifically:
React.useEffect(() => {
// Create an async function...
async function runEffect() {
const url = `${API}/get-profile?id=${userId}`;
const res = await fetch(url);
const json = await res.json(); <-- OK
setUser(json); <--- Wrong.
}
```This is, hands down, the #1 mistake that react developers make. I've seen it literally in every react code base I've ever opened (if the code base had any kind of `fetch` in it).
It's covered in the documentation now, explicitly:
https://beta.reactjs.org/learn/synchronizing-with-effects#fe...
This is a prime example of a sharp edge with react hooks; it's a very very common pattern, but because people don't understand what's going on, they do it wrong naively; and even when you do know it's wrong, it's a rare edge-case that causes an invisible bug ("Tried to update a component that wasn't mounted...") and makes code messy and hard to read.
The tldr should be: Do not use async effects. Use suspense.
> Do not use async effects. Use suspense.
The linked documentation does not mention the word "suspense".
Do you have a link that combines these two topics?
Instead the React docs explain a workaround that leads to completely different network request behaviour across development and production:
> In development, you will see two fetches in the Network tab. > In production, there will only be one request.
The proposed solution in the docs now:
> useSomeDataLibrary()
without saying what that "some data library" could be.
I have to wonder how much pain would have been saved if the React team had just shipped a `usePromise` hook years ago.
"await blocks" on http://web.archive.org/web/20180103230006/http://svelte.tech...
Curiously, it's also very similar to the example in the beta docs that wokwokwok just linked to.
> Missing whitespace. I've since realized that there is no perfect solution to this problem.
Indeed :)
HTML had the same problem, albeit with different and equally frustrating choices.
The problem is inherent to markup languages: difficulty separating intentional content from internal formatting. That is the both the feature and bug of markup.
Was disillusioned when I had to dive into a pure js project using React.
The real benefit, I think, is that you get the well established Clojure idioms around isolating and managing mutable state.
State is stored in a Atom, which is atomically mutated, and reactive components essentially 'subscribe' to updates upon that atom to re render.
The mutations can be handled centrally by a message queue, but really, event sourcing like that is not always needed.
But I believe what OP meant is really more about how these idioms are holistically implemented throughout Clojure. Whereas in JS we have to fight the language quite often.
I went into this period of debate with what I feel is an open mind. Open to the possibility that react really is overrated and more trouble than it's worth.
But after writing this app I'm very well reminded of why I was so enthusiastic about react way back when. Handling state updates in vanilla JavaScript is quite messy.
Then again, react is far from a perfect solution to the problem. It adds about as much complications as it takes away.
I hope we can find better solutions. But I'm not sure how to move forward when it seems so hard to agree on what the problem is.
(1a) is the web’s desire to mix “ui rendering” with “state management” which are two different things.
How would your approach at seperating state from UI look like?
There will be cases where Unpoly (which can do quite a lot) only does 95% (or whatever) of your requirements. In those cases you can sprinkle in a bit of Vanilla JS to help fill the gap. Additionally, there will be some cases where Unpoly isn't at all suitable, like if you're building something that is extremely interactive (i.e. the next Google Docs/Maps or similar). However, those cases keep getting smaller as these LowJS Frameworks improve. Everyone's case is a very particular set of circumstances and this might not apply at all to your situation, but others are finding success with using HTML over the wire types of approaches. [3] One final thing to note that's often overlooked is that CSS' capabilities are growing, and can do a more than in the past. All things to think about before reflexively defaulting to React.
[1] https://unpoly.com/up.layer
[2] https://unpoly.com/tutorial
[3] https://htmx.org/essays/a-real-world-react-to-htmx-port/
I think this is where your proposition causes me to raise an eyebrow.
If you can stay 100% within your framework then I can accept it will be simpler and more productive than React.
But this architecture of “95% in-framework and 5% JavaScript spaghetti”… I don’t trust that. That sounds like a lot of days burnt trying to bolt that one feature onto a framework that doesn’t support them. And a lot of days debugging into the framework internals to try to understand which possible implementation of that feature won’t blow up by crossing some assumption of the framework. And I’m not sure you can argue as convincingly that’s less effort than the 100% React solution.
IMO the beauty of React is you can do anything you’re asked to do. There’s alway a “React-y” way to do something. That’s because it’s lower level than a framework. It’s just a set of primitives. And pretty well thought out, battle tested primitives at that.
And, when you do it right, you can have a very large piece of software that’s made entirely of small, functional modules. And there are simple rules for following the control flow. Once you understand those rules (and it does take a few years to really grok them) then you can drop in to any module in a massive system and follow the control flow easily.
In a framework you don’t have that. There’s various points where your code calls into some declarative interface the framework has exposed, and then *magic happens* and the wrong behavior pops out on some other end of the application. It’s a debugging brick wall and in my experience it’s a massive time sink. Even in React many third party libraries also put you in this position, but that’s a whole other rant…
But that is React’s superpower: when you use it correctly your time spent debugging any one defect is closer to O(1). With more “black box” frameworks your debugging time can be more like O(n), where n is the size of the codebase.
For small codebases, there’s no difference, or maybe the framework is faster even. But for large codebases I think React has a massive productivity boost there.
And all of this is predicated on that 5% number you quoted. If you can stay 100% within the framework, go for it. But in my experience business needs are always going be pushing 5%, 10%, 20% of the “special requests” and if you don’t plan for that, they can start taking up 50%, 60%, 70% of your time.
There were thousands of pre-react desktop apps on frameworks from turbovision to *tk to appkit and not a single one of them mismanaged focus because of a missing “key” or required to “update state through slicing an array” nonsense. This old pain you feel is historically self-inflicted and doesn’t exist elsewhere.
I made a bunch of apps and user interfaces with these frameworks myself. It was natural and straightforward. Sometimes it could get clunky and hack-y due to limitations, but usually it was the level when a whole react team would be fired for economical reasons (think of multi-tab forms with settings, dialogs, master-details, complex table input, etc).
Edit: “slicing”
Frankly, Flex did s lot of things right. The layout and the default widget library was top notch. The grid was a killer feature. The IDE was really helpful.
And second, not at all. E4X existed in the 2000s and was widely implemented in Firefox (then the biggest modern browser) and Flash (the other de facto runtime). E4X let you embed XML directly in JS and you basically were able to build React-style templating without the preprocesor that React requires.
So basically the world has been working on something like React for 2 decades. React just is so far the best version of SGML in code.
full syllabus here: https://fullstackopen.com/en/#course-contents
const [state, setState] = useHook("a")
...
setState("b")
console.log(state)
I could imagine React adopting Signals and ending up with something like: const [accessor, setState] = useSignal("a")
...
setState("b")
console.log(accessor())I wonder how Preact works with Signals, then?
The default behavior is that _if_ there are any changes that are needed based on the render, React then continues ahead and applies them to the DOM, and most of the time that is done immediately.
When a render is queued, React keeps the info about the requested state update as part of the queue, and those state changes are calculated and applied as part of the "render phase". So, if you happen to call `setState(2); setState(3);`, the second call completely overrides the first and there won't even be an attempt to render the component using the `2` value. (You can use the `setState(prevValue => 3)` form to force React to do each value separately.)
As of React 18, the new "concurrent rendering" features like `startTransition` and Suspense allow React to alter priorities of renders, and split the calculation into multiple chunks over time with pauses in between. When React _is_ done determining any changes in that render pass, it still applies them to the DOM in a single synchronous "commit phase".
The other caveat is that React will sometimes execute a full render+commit synchronously under specific conditions, such as a `setState` inside of a `useLayoutEffect` hook.
I wrote an extensive detailed post called "A (Mostly) Complete Guide to React Rendering Behavior" that tries to explain a lot of these nuances:
- https://blog.isquaredsoftware.com/2020/05/blogged-answers-a-...
function handleAddItem(value) {
const nextItems = [...items, value];
setItems(nextItems);
}
should be? function handleAddItem(value) {
setItems(items => [...items, value]);
}It’s not that it doesn’t work, it does.
But I’ve found there are basically two scenarios:
1) Simple cases where there’s no risk of contention and you can just operate as if your state variable is up-to-date.
2) Complex cases where you have state changes coming from multiple directions and contention is a concern.
In the second scenario I just go straight to useReducer. It is much more reliable than useState when there is the possibility of contention. And it’s much easier to reason about than having a bunch of setState calls all over.
IMO the setState((oldState) => newState) pattern is a half measure that’s almost never the best choice.
Any thought on signals? They seem to be hyped as the next big thing for managing state, haven't used them myself yet though.
But I haven’t used them personally so I don’t know. Will be interesting to see how folks do with them.
It might come back and bite you if you implement something that performs an async update of that state via a different path later.
So by me not so much trite as faux pas.
:)
Cue the downvotes....
For example the "Accessing state after changing it" has absolutely nothing to do with React or async code, and everything to do with the scope of the count variable and how JavaScript passes numbers by value.
React, otoh, provides methods that access and update state. React’s handling of changing state using these methods is to queue the change, not to update it immediately.
function handleClick() {
setCount(count + 1);
console.log({ count });
}
Since count is enclosed within the function, it could be mutated by _anything_. In isolation, you can't really be sure of what setCount does, since the "count + 1" statement passes a completely new value unrelated to count.If setCount didn't have any side effects, it is an obvious mistake to assume the value of "count" would have changed.
So if the intention is to log the incremented count, it is bad code in any situation, React or not.
What you’re saying amounts to “functions/methods can do whatever they want, and assuming they do what they claim to do is an obvious mistake.”
export function deepClone<T>(obj: T): T {
if (obj == null || typeof obj !== 'object')
return obj;
const clone = new (obj as any).constructor();
for (let key in obj) {
if (obj.hasOwnProperty(key))
clone[key] = deepClone(obj[key]);
}
return clone;
}A correct immutable update is more like a "nested shallow update", copying all levels of nested keypaths leading to the actual value you want to update.
If you prefer to avoid writing those immutable operations by hand, Immer is a fantastic tool for simplifying the code by using "mutating" syntax that gets turned into a safe and correct immutable update:
- https://immerjs.github.io/immer/
- https://beta.reactjs.org/learn/updating-objects-in-state#wri...
We even use Immer by default in Redux Toolkit:
So yes, if you have a nested object with a bunch of different fields, and you update `state.a.b.c = 123`, it makes copies of `b`, `a`, and `state`, but preserves all other nested references that are anywhere inside of `state`.
It's the same as if you wrote:
return {
...state,
a: {
...state.a,
b: {
...state.a.b,
c: 123
}
}
}
but obviously much shorter and easier to read / maintain :)It also conveniently eliminates the chance of a _real_ accidental mutation (which in the case of Redux was always the #1 cause of bugs in Redux apps).
In cases where I want to get ideal performance, I sometimes separate out a plain JavaScript service and wrap it in a React hook.
So for example, let’s say you have a massive array of like 100,000 objects. You presumably aren’t putting that entire array on the screen at once. So you could keep the array in a normal JavaScript class, keep in instance of that class in state, fire events into it, and then query out the slices of data you actually need.
Those smaller slices can be generated each time there is a state change, but you don’t need to re-allocate the big array.
Even if you do need to show the entire array, say as a data plot, you can render directly to a canvas, but still wrap that canvas and the I/O in a React hook. React works quite well with these “plain JavaScript” escape hatches in the rare case they’re needed.
The other place I’ve been using this approach is for drag and drop hooks, where the complexity of managing React renders and coordinating state changes on every mouse move is just too much. Instead I have service class that updates the few DOM nodes that need to be changed every frame, and I only fire off state changes when there are meaningful transitions (hover over something, drop something, etc.)
It's not that expensive. You don't need to deep clone an array to change one element, you just create a new array linking to all the old elements, except the one you want to change plus the new version. If you understand "referential equality", this will make a lot more sense.
For example:
const [largeArray, setLargeArray] = useState<MyObj[]>([]);
const updateObject = (index: number) => (newObj: MyObj) => {
setLargeArray(prevArray => ([
...prevArray.slice(0, index),
newObj,
...prevArray.slice(index+1),
]));
}PS Why did you post code a `deepClone` function? You certainly don't need to deep clone.