News for hackers. Stuff that matters.
Re:React Common Tools and Practices: State Management Overview by IceHegel on Monday March 08, 2021 @10:15AM (#26386590)
If any react noobs are reading this, the best React state management setup for you is Redux+Immer. After some setup, it's easy to use, and the docs are very good and up to date.

When I was learning React, I kept putting off Redux because youtube said it was complicated and you didn't need it after useContext. Big mistake. Our app became more complicated because our state management(useState/useContext) was so simple. Switching to Redux dramatically simplified our most complicated components.

Also, the Redux dev tools extension is a game changer. It lets you see every state change, in order, with traces and diffs.

https://github.com/zalmoxisus/redux-devtools-extension

Pros can obviously make up their own mind. I’ve tried Mobx and the tooling just wasn’t there, but I hear their diffing algos are good.

Re:React Common Tools and Practices: State Management Overview by jeswin on Monday March 08, 2021 @10:34AM (#26386788)
> If any react noobs are reading this, the best React state management setup for you is Redux+Immer.

React noobs should just stick to React's own useState and useContext hooks. There are issues with it, but it's not as bad.

Here's what Pete Hunt from the original React team said last week: "Literally never ever use Redux on a new project under any circumstances. Even if it’s what the team knows." [1]

1: https://twitter.com/floydophone/status/1365824299060273153?s...

Re:React Common Tools and Practices: State Management Overview by acemarke on Monday March 08, 2021 @10:41AM (#26386856)
I pressed Pete on what he actually meant by that in the replies [0]. Eventually he listed some specific concerns:

- The React ecosystem has fragmentation because there's many ways to do things, and he feels someone needs to start narrowing down suggestions to reduce confusion.

- There was an article going around on "Why I'll Never Use React for Enterprise Apps Again", and half of the problems listed in the article were about Redux and React ecosystem related issues instead of React itself, so Pete's upset about that

- Pete feels opinionated data fetching tools and explicit state machines solve some use cases better

- Pete thinks it's too hard to dynamically code-split Redux logic

So, those are valid technical points that can be discussed in detail. But those are also a very far cry from "NEVER EVER USE REDUX!", and I'm really not sure how you jump from "one article said they had trouble migrating their code from `connect` to hooks and they aren't happy with Redux-Saga" to "NEVER USE REDUX" either.

I actually pointed out that we have a new upcoming "RTK Query" API that's in alpha right now [2] that drastically simplifies data fetching and caching for Redux, and Pete said later in that thread he thought it looked impressive. He also said he appreciates the work put into Redux Toolkit and our docs updates.

So yeah, Pete said that, but as usual there's a lot more nuance in the later discussion that should be highlighted rather than the clickbait-y initial tweet.

[0] https://twitter.com/acemarke/status/1365824897210064897

[1] https://betterprogramming.pub/i-almost-got-fired-for-choosin...

[2] https://rtk-query-docs.netlify.app

Re:React Common Tools and Practices: State Management Overview by ericwood on Monday March 08, 2021 @10:50AM (#26386955)
I've found this works so much better than reaching for state management libraries off the bat. Most of the time it's overkill and the complex state transforms really only affect a few parts of the application, in which case useContext and useReducer can help immensely.

Learning the built-in React features goes a longer way than specific state management libraries if you're starting out. I'm really wary of anyone selling a specific set of libraries as being the way for beginners to go, unless they're tackling apps that have very specific state management needs.

Re:React Common Tools and Practices: State Management Overview by acemarke on Monday March 08, 2021 @10:54AM (#26387004)
FWIW, I completely agree that people should focus on learning React itself first, and then pick up other libraries (like Redux) later, and we specifically make that recommendation in the Redux docs.

That's also the kind of advice I want to have in this new "Community Tools" resource site. At the same time, this site _is_ intended to list common tools in use in the ecosystem and when it _might_ make sense to use them.

Re:React Common Tools and Practices: State Management Overview by ericwood on Monday March 08, 2021 @11:00AM (#26387082)
This is more commentary on the "the best React state management setup for you is..." comment above than the site itself. I fundamentally take issue with there being a "best" solution for state management, especially targeted at people starting out. The various libraries can do great things for different apps, but the answers as to what works best for a given situation tend to be nuanced.
Re:React Common Tools and Practices: State Management Overview by Chris_Newton on Monday March 08, 2021 @12:11PM (#26388257)
There can’t be a universal best solution to state management. Sometimes your requirements are so simple that using a library is overkill and basic JS is fine. Sometimes your requirements are so complicated that well-known libraries like Redux and MobX aren’t enough, and if you’re going to implement something more comprehensive anyway then the extra dependency might not be helpful. In between, there is a scale where different strategies might work best. A site that helps less experienced developers to figure out where their needs fall on the spectrum and which strategies might work well for them seems like a helpful idea.
Re:React Common Tools and Practices: State Management Overview by ericwood on Monday March 08, 2021 @12:27PM (#26388527)
I agree, once again my original comment is in response to a comment on here that I'm replying to and not the linked article. I myself would find a lot of utility in a site that compares all the different approaches.
Re:React Common Tools and Practices: State Management Overview by Chris_Newton on Monday March 08, 2021 @02:45PM (#26390566)
I was commenting in support of your position. Sorry if that wasn’t clear!
Re:React Common Tools and Practices: State Management Overview by IceHegel on Wednesday March 10, 2021 @10:45AM (#26412411)
I take the point that "best" isn't completely objective, but it's also important for people with experience to help those learning the ecosystem. The state management players differ in philosophy and quality. I’m not sure Redux is abstractly the best state management pattern, but practically it’s a very high quality library with native-app quality tooling.
Re:React Common Tools and Practices: State Management Overview by IceHegel on Wednesday March 10, 2021 @10:34AM (#26412290)
Completely agree that anyone learning React should learn the built in patterns first. My point was that if your app is becoming meaningfully more complicated because you are working around the limits or useState and useContext, you should not hesitate to learn and use Redux, even in 2021.
Re:React Common Tools and Practices: State Management Overview by richeyryan on Monday March 08, 2021 @10:57AM (#26387040)
Good rule of thumb is to disregard any statement like "Literally never ever ... under any circumstances" irregardless of the supposed reputability of the person saying it. Its either purposely meant to be a hot take to rile people up or its lacking nuance.

As other comments have mentioned, he has valid concerns and some opinions about what a preferable architecture looks like but for whatever reason he chose not to lead with that.

Re:React Common Tools and Practices: State Management Overview by jeswin on Monday March 08, 2021 @11:05AM (#26387153)
Redux became a thing because of Dan Abromov's impressive tutoring and documenting skills early on and due to acemarke being a good leader after he left.

It's a nice pattern but in an artistic sense.

Changing UI state 10 years back:

state.totals = 100;

Changing state today:

1. Call an action creator

2. Dispatch an action to the reducer

3. Switch by action type

4. Apply action on state

5. Return new state

So imho the problems start right at the bottom - the extreme verbosity and the redundancy.

Re:React Common Tools and Practices: State Management Overview by richeyryan on Monday March 08, 2021 @11:18AM (#26387349)
I'm not saying anything about the actual tools here. I have an opinion of course but that's not relevant here. What I'm saying is most technical decisions require nuance and thought. If someone is presenting a thought without any room for nuance, it probably doesn't stand up to scrutiny. What the frontend community needs is more honest and nuanced appraisals of tech and less cargo culting.

Most people take umbridge because Redux was cargo culted in the first place, cargo culting against it isn't that helpful. I think the website shared in this post is a great approach. Show everyone the options and let them decide what solution fits their problem.

Re:React Common Tools and Practices: State Management Overview by phryneas on Monday March 08, 2021 @11:12AM (#26387262)
That does not sound like you are up-to-date with what the official redux tutorials currently recommend for writing modern redux. https://redux.js.org/tutorials/fundamentals/part-8-modern-re...

Also, two-way-data-bindings like just `state.totals` work when you're just re-rendering your whole app on every frame, but as soon as you get away from that, there will always be either some "observing" or "signalling" involved to trigger rerendering of the correct parts of your application. Redux goes the "signalling" way, MobX goes the "observing" way, both have their benefits and drawbacks.

Re:React Common Tools and Practices: State Management Overview by dmitriid on Monday March 08, 2021 @11:48AM (#26387885)
> That does not sound like you are up-to-date with what the official redux tutorials currently recommend for writing modern redux. https://redux.js.org/tutorials/fundamentals/part-8-modern-re...

--- start quote ---

import { combineReducers } from 'redux'

import { createStore, applyMiddleware } from 'redux'

import thunkMiddleware from 'redux-thunk'

const composedEnhancer = composeWithDevTools(applyMiddleware(thunkMiddleware))

import { createSlice } from '@reduxjs/toolkit'

...createSlice will automatically generate action creators

--- end quote ---

It's.... it's not better in any way?

> Redux goes the "signalling" way, MobX goes the "observing" way, both have their benefits and drawbacks.

I like Svelte's approach. Where they figure out which things are being observed or changed at compilation/transpilation time and generate code for that case specifically.

Re:React Common Tools and Practices: State Management Overview by phryneas on Monday March 08, 2021 @12:02PM (#26388111)
That page introduces one tool after another, replacing all those external tools with the officially recommended Redux Toolkit that wires all of them up for you.

In the end you are left with only

`import { configureStore, createSlice } from '@reduxjs/toolkit'`

Re:React Common Tools and Practices: State Management Overview by dmitriid on Monday March 08, 2021 @12:41PM (#26388787)
> That page introduces one tool after another, replacing all those external tools with the officially recommended Redux Toolkit

Perhaps. As person who's never used thunks or, really, half of those tools in conjunction with Redux, this tutorial is quite confusing.

> In the end you are left with only import { configureStore, createSlice } from '@reduxjs/toolkit'

The final code on the page is literally

  import {
    createSlice,
    createSelector,
    createAsyncThunk,
    createEntityAdapter
  } from '@reduxjs/toolkit'

The page doesn't really address the issue of verbosity and the flow as described in the original comment. It just hides some of it behind some facades with autogenerated accessor functions (so, even more levels of abstractions).
Re:React Common Tools and Practices: State Management Overview by acemarke on Monday March 08, 2021 @12:48PM (#26388926)
Yes, the entire point of that page is:

- You've gone through this whole tutorial sequence and should now understand how to write all this Redux logic "by hand" and why these standard Redux usage patterns exist

- Now, here's how Redux Toolkit abstracts and simplifies those exact same patterns, so that you can do the same thing with less code, but you understand what those abstractions are doing for you internally.

Re:React Common Tools and Practices: State Management Overview by jeswin on Monday March 08, 2021 @11:18AM (#26387347)
What's one good reason why JS proxies (which let you listen to "state.totals = 100") aren't a cleaner solution to trigger a rerender?

There's no need to rerender the whole frame - will be happy to provide an example on request.

Re:React Common Tools and Practices: State Management Overview by phryneas on Monday March 08, 2021 @12:06PM (#26388155)
That would be the "observing" approach I described.

The upside of an action-based (signalling) approach is that you have a better time separating concerns as actions (if used correctly) represent intent, so your component emits an event and the state acts accordingly, removing state logic from your representational components. Might also be a lot easier to see in the DevTools what happened when and why.

Of course not every app needs a pattern like that, that's why I said both approaches are valid.

Re:React Common Tools and Practices: State Management Overview by jeswin on Monday March 08, 2021 @12:31PM (#26388608)
My point is that the action-based approach you describe is extremely verbose for very little gain. Most apps don't need it, yet that's what Redux forces you to do.

Regarding DevTools, it's just as easy to make it work with "observing".

Also, I'm not saying you should write state changes and data fetching in the UI components. By all means write them under actions/services whatever. I'm complaining about the complexity around effecting that change.

Re:React Common Tools and Practices: State Management Overview by phryneas on Monday March 08, 2021 @12:50PM (#26388950)
It doesn't seem verbose to me. Have you looked into those docs above? You define a reducer and an action creator is automatically generated. String action types are an implementation detail. No manual immutable state modification, as immer is baked in. Modern redux is maybe 20% of what you might be imagining if you only know legacy redux.

It's not much more code than writing a function, but other reducers of your state can suddenly act upon the same action, you can trigger side effects using middleware and of course watch stuff "by intent" and not "there was a modification" in the devtools. All while keeping everything separated pretty well.

Re:React Common Tools and Practices: State Management Overview by IceHegel on Wednesday March 10, 2021 @10:56AM (#26412535)
More steps can be good if they clarify thinking (Typescript) and make code more intuitive. Complex apps have complex state and Redux handles that really well. It might no be needed for a TODO list tutorial, but comments like these are what prevented me learning Redux (I was like wtf are dispatch, action, thunk - seems lame) when it's actually a great tool that often reduces complexity.

Also, with action factory, step 1 can be automated.

Re:React Common Tools and Practices: State Management Overview by acemarke on Wednesday March 10, 2021 @05:10PM (#26417034)
Note that our official Redux Toolkit package is the recommended approach for writing Redux logic:

https://redux-toolkit.js.org

https://redux.js.org/tutorials/fundamentals/part-8-modern-re...

It doesn't eliminate the "dispatch actions" concept, because that's core to how Redux works. But, it does simplify the vast majority of your Redux logic considerably.

Re:React Common Tools and Practices: State Management Overview by dsego on Monday March 08, 2021 @10:42AM (#26386867)
What about something like zustand? https://zustand.surge.sh/
Re:React Common Tools and Practices: State Management Overview by acemarke on Monday March 08, 2021 @10:19AM (#26386631)
To be clear, we now specifically teach that our official Redux Toolkit package is the standard approach for writing Redux logic [0]. RTK uses Immer internally by default [1], and I actually just wrote a brand new "Writing Reducers with Immer" usage guide page yesterday [2].

All that said, this new "React Community Tools" site isn't intended to specifically plug Redux or recommend it instead of other tools. I want it to be a catalog and informational site that helps people understand what tools are out there and what problems they solve, so that they can make decisions about what tools to use based on their own needs and applications. I just happened to write a Redux page first because that's what I know about, and I wanted at least one draft page up there so that we can nail down what some of the content structure for these pages should look like and use that as a basis for getting people to contribute pages for other tools.

[0] https://redux.js.org/tutorials/essentials/part-2-app-structu...

[1] https://redux.js.org/tutorials/fundamentals/part-8-modern-re...

[2] https://redux-toolkit.js.org/usage/immer-reducers

Re:React Common Tools and Practices: State Management Overview by arvigeus on Monday March 08, 2021 @10:23AM (#26386668)
I managed to replicate Redux Toolkit api with context and hooks. Still, would not recommend it over Redux for performance reasons.
Re:React Common Tools and Practices: State Management Overview by PragmaticPulp on Monday March 08, 2021 @10:26AM (#26386696)
Good place to start.

Most important for beginners is to pick one state management solution and learn it quickly. Don’t waste time touring all of the options or trying everything. Pick one, learn it well, and get it going. You can evaluate alternatives after you understand the basics of one system.

Re:React Common Tools and Practices: State Management Overview by christiansakai on Monday March 08, 2021 @10:33AM (#26386763)
Why do we need Immer? Can't we just do our object copying ourselves? It seems using Immer it can break dev's intuition about pass by reference and performance.
Re:React Common Tools and Practices: State Management Overview by acemarke on Monday March 08, 2021 @10:44AM (#26386907)
You don't _need_ Immer. But:

- Writing immutable update logic by hand is really hard to do correctly and hard to read

- Accidental mutations have historically been the number one cause of bugs in Redux apps

Immer eliminates accidental mutations, and makes it _way_ easier to write and read code that does correct immutable updates.

So, we now recommend Immer as the right way to do immutable updates in Redux [0], and Redux Toolkit uses it by default [1].

Agreed that there is absolutely a learning curve aspect here - you need to know why and how to write immutable updates by hand to really appreciate what Immer is doing for you, which is why I've repeatedly highlighted that information in our docs [2].

[0] https://redux.js.org/style-guide/style-guide#use-immer-for-w...

[1] https://redux.js.org/tutorials/fundamentals/part-8-modern-re...

[2] https://redux-toolkit.js.org/usage/immer-reducers

Re:React Common Tools and Practices: State Management Overview by pgsandstrom on Tuesday March 09, 2021 @07:05AM (#26398025)
Maybe Im missing something, but why not simple do a deep clone of the state object and then modify the deep clone?
Re:React Common Tools and Practices: State Management Overview by acemarke on Tuesday March 09, 2021 @09:05AM (#26398817)
A deep clone is _not_ what you want here. A correct immutable update is better described as a "nested shallow clone", where you copy each specific level of nesting from the root down to the value(s) you actually want to change.

A deep clone would result in unnecessarily copying a bunch of extra objects and arrays that aren't relevant, so that's a waste of cycles. On top of that, the React ecosystem (and React-Redux in particular) relies on reference comparisons to determine if data has changed. If you copy objects that didn't actually get updated, it can cause a lot of components to re-render when they really shouldn't have.

For more details see:

- Dave Ceddia's "Complete Guide to Immutability in React and Redux": https://daveceddia.com/react-redux-immutability-guide/

- The Redux docs page on "Immutable Update Patterns": https://redux.js.org/recipes/structuring-reducers/immutable-...

- The Redux FAQ entry on deep cloning: https://redux.js.org/faq/performance#do-i-have-to-deep-clone...

- The Redux FAQ page on immutability: https://redux.js.org/faq/immutable-data

Re:React Common Tools and Practices: State Management Overview by IceHegel on Wednesday March 10, 2021 @11:13AM (#26412759)
This will work but isn't advised.

- Bad: newX = JSON.parse(JSON.stringify(x))

- Slightly Better: newX = lodash.cloneDeep(x)

- Best(using immer): newX = produce(x, draftX => {draftX[1].done = true})

I don't know how JavaScript engines actually assign memory, but I think of object references in JavaScript like pointers in C. If you deep clone you're copying way more than you need, mallocing giant blocks of memory for duplicated data. Libraries like immer(the best) and immutable.js will only copy what you changed, which saves time and memory.

Re:React Common Tools and Practices: State Management Overview by boredpandas777 on Monday March 08, 2021 @11:05AM (#26387147)
<<It lets you see every state change, in order, >>

In general, if we use any async APIs in your JS that modify shared state the order will consist of an interleaving of all events, including from timers (macrotasks), DOM events (macrotasks), resolved and finalized promises (microtasks) and DOM APIs like IntersectionObserver (microtask), IDB et al, along with synchronous calls (including any recursive calls) so looking at things in order does not mean anything in a complex UI with lots of interleaved events if you cannot filter by a named action (the action that caused a certain chain of events, which otherwise will be displayed intermingled with all other events from other actions) you can't really follow the data and control flow of your app. So order only matters in debugging and comprehension if you can filter by action. Another thing we should care about is domain driven design and domain aggregates for your state store to make sure that only one aggregate root is responsible for a given part of state. If more than one chain of events (more than one named action) modify the same part of state then trying to comprehend the relationship between state and action becomes too complicated and you lose consistency guarantee as a result (overlapping and interleaving reads and writes) unless you introduce some form of MVCC (multi-version concurrency control)

I've built tools to visualize how complex highly concurrent UIs work under the hood and found the principles and methods to be directly applicable to analysis of microservices based apps.

Re:React Common Tools and Practices: State Management Overview by hesarenu on Monday March 08, 2021 @11:23AM (#26387419)
I have replaced redux with just react-query and hook,context. Simple for noobs as well.
Re:React Common Tools and Practices: State Management Overview by nawgz on Monday March 08, 2021 @11:06AM (#26387169)
Immer seems like it lets you take the same approach as mobx, but instead of rerendering based on an optimized run-time constructed dependency graph, Immer has to rebuild every single item "under" your mutation. Doesn't this seem like it would be insanely expensive for modifying arrays or things like this?

I also have to imagine the amount of boilerplate you write to use Redux + Immer is orders of magnitude over mobx, but maybe some people prefer it to be slightly more explicit

Re:React Common Tools and Practices: State Management Overview by acemarke on Monday March 08, 2021 @11:39AM (#26387712)
Immutable updates in JS have always required making copies of each level of nesting that has to be updated [0].

However, that process is very tedious and error-prone due to writing lots of nested spread operations.

Immer effectively does those same steps, but automatically. This is all completely different than how Mobx works.

Immer has a slight performance overhead [1], but in practice reducer logic is almost never a meaningful perf bottleneck in a React+Redux app - the cost of updating the UI is might higher.

It's also worth noting that Immer was actually created by Michel Weststrate, the author of Mobx :)

[0] https://redux-toolkit.js.org/usage/immer-reducers#basics-of-...

[1] https://immerjs.github.io/immer/docs/performance

Re:React Common Tools and Practices: State Management Overview by nawgz on Monday March 08, 2021 @11:59AM (#26388068)
Yes, absolutely that is my understanding of immutability. It's why I asked the performance question, but Immer docs are convincing, I see your point.

Not a surprise to me that mwestrate is the author after seeing the description of Immer - he has an excellent graph knowledge and applies clever architectures & optimizations from that.

I recognize it's completely different from how MobX works, I simply mean to say that I feel MobX is superior and this mere idea of mutability / copying instead of smartly updating a graph and correspondingly only the observer portions of your UI seems like the core of that