by acemarke · 6y ago · 0 comments
In order:
Thunks are the most widely used middleware by a large margin [0], and we have frequently received complaints that there is no async middleware included in the Redux store by default. Thunks were in fact part of the store during the original development phase [1], but were made separate once the middleware API was defined [2]. Thunks are effectively the minimum viable way to write async logic that has access to interacting with the Redux store, so we include that in RTK out of the box to make that possible.
Sagas, observables, and other similar middleware are far too heavyweight and complex for us to endorse as the default async approach. I also strongly disagree that thunks are an "anti-pattern", and find them to be a highly useful tool (and especially so now that `async/await` syntax makes it even easier to write more complicated async logic in a readable form) [3].
You are always welcome to add another middleware or disable thunks as part of the store setup process instead if you want.
I don't see how this:
const addTodo = createAction("todos/add")
is more verbose than this: const addTodo = (text) => {
return {
type: "todos/add",
payload: text
}
}
We've had a version of `createReducer` shown in the "Reducing Boilerplate" docs page [4] for years, and there are literally hundreds of similar "lookup table"-type utilities out there. Including this in RTK is a no-brainer. It's even more valuable, because ours uses Immer inside to let you write "mutative" immutable update logic instead of having to nest spread operators. I don't see how this is "obscuring" anything.Finally, our recommendation is that most of the time you shouldn't even be calling `createAction` and `createReducer` yourself. Instead, you should be using the `createSlice` function [5], which automatically generates action creators and action types for you, and calls the other two functions internally.
[0] Slide 38 in https://blog.isquaredsoftware.com/2017/09/presentation-might...
[1] https://github.com/reduxjs/redux/issues/1
[2] https://github.com/reduxjs/redux/pull/63#issuecomment-110575...
[3] https://blog.isquaredsoftware.com/2017/01/idiomatic-redux-th...
[4] https://redux.js.org/recipes/reducing-boilerplate#generating...
There's no functional difference between using redux-thunk and just calling a "global" `dispatch` in random callbacks; both are equally unmaintainable in the face of interacting effects.
EDIT: Having a bunch of complex async logic all modifying your store in overlapping ways without careful coordination is like having concurrent operations on your database without any transactions or locking.
createAction I don't think we'd ever use, and I'd recommend against it - multiple explicit function arguments instead of a payload blob is much easier to understand when reading the code, and the action function should use those arguments to create the blob. Your example here makes sense simply because the blob appears to be a single string value, rather than say, id+value, or even something more complex.
createSlice, to me, appears to be adding a lot of complexity for no apparent benefit. I even had to read through it a second time before I realized extraReducers was the escape hatch to avoid the action=reducer antipattern, but the structure definitely still seems to be promoting it, where actions are defined as part of a set of reducers, then reused elsewhere if need be.
However, yes, there are many cases where you might want to accept multiple arguments for an action creator, do additional work to define the contents of the payload, or generate unique IDs as part of creating the action. That's why `createAction` also accepts a "prepare callback" as its second argument [0] [1].
`createSlice`'s primary benefit is to remove the need to write action types and action creators by hand. All you have to do is write your reducer functions, give them meaningful names, and you get the action generated creators for free (and the action types effectively become an invisible implementation detail).
We've always told folks that it is not required to have a 1:1 mapping between action types and reducers [2] and that many reducers can respond to a single action [3], but realistically speaking, most actions _are_ only handled by one reducer. Again, `createSlice` handles that 80% use case by generating actions that correspond to that given case reducer in the `reducers` argument, but also allow you to handle the "events" case by listening for other actions in the `extraReducers` argument. (And, the `reducers` argument allows defining "prepare callbacks" as well if desired [4]).
So, in both of these APIs, we solve the 80% use case by default, but allow handling the additional 20% if desired.
Most folks won't need to be calling `createAction` themselves given the existence of `createSlice`, but there's no reason to _not_ have it as part of the public API (especially since `createSlice` already uses it internally).
[0] https://redux-toolkit.js.org/api/createAction#using-prepare-...
[1] https://redux-toolkit.js.org/tutorials/intermediate-tutorial...
[2] https://redux.js.org/faq/actions#is-there-always-a-one-to-on...
[3] https://redux.js.org/style-guide/style-guide#model-actions-a...
[4] https://redux-toolkit.js.org/api/createSlice#customizing-gen...
Actions are ALWAYS action(payload) => { type: action, payload }
There's no reason to call a function everywhere you need a new action. Just define all of them in one place by listing the types. You can easily write a function that looks like
createActions(['TODOS/ADD', 'TODOS/DELETE', ... ]})
That returns all your action creators and types in one place. Import them as needed.The above single call function to create a todo action is verbose without achieving any efficiency. It's bad design.
Don't get rid of the switch statements at all. Use them. They're clear. If you need to slice things up, just use child reducers in the switch branches. Lookup tables are less performant and don't buy you anything.
Sorry to be so harsh but this kind of cargo-cult best practice stuff is how you end up with Javascript that feels like Enterprise Java™ from back in the 00s.
We officially recommend consistently using action creators [0], and I talked about the reasons to use them in a blog post [1].
Switch statements and lookups are almost completely equivalent (except for fall-through and default case handling) [2], and "performance" is irrelevant here. In this case, use of `createSlice` means that writing the lookup table object generates the resulting action types and action creators for free, which drastically reduces the amount of code you have to write.
I am strongly against defining async logic inside of `mapDispatch`. It's similar to writing thunks in the first place (an arbitrary function that has access to `dispatch`), but it's less testable, not reusable, _and_ doesn't have access to `getState`. In fact, you should be using the "object shorthand" form of `mapDispatch` [3] to pass action creators into connected components, like `const mapDispatch = {addTodo, toggleTodo}`.
The advice to put async logic in `mapDispatch` also does not help if you're using our new React-Redux hooks API [4], where you just have `const dispatch = useDispatch()`.
The Redux Toolkit API is specifically designed to remove as much as possible of that incidental complexity from your Redux code, and move it _away_ from being that "Enterprise Java" feel.
[0] https://redux.js.org/style-guide/style-guide#use-action-crea...
[1] https://blog.isquaredsoftware.com/2016/10/idiomatic-redux-wh...
[2] https://blog.isquaredsoftware.com/2017/05/idiomatic-redux-ta...
[3] https://redux.js.org/style-guide/style-guide#use-the-object-...
So yes. We disagree strongly but it's because you are outright wrong in your claims. Putting function calls in mapDispatch does not do anything to their reusability or their testability. They're still functions. You're making taste claims but treating them like they are factual.
If you're wondering why my tone is so dismissive it's because yours is so prescriptive. I've worked on a lot of react and redux projects and I know my way around. If you're attempting to reify your development taste into a framework of "best practices" you need to be prepared for criticism. Responding to me with footnoted appeals to authority does nothing for your argument.
The docs content and recommendations are based specifically on the questions I've seen asked, the ways I've seen Redux used, and the concerns I've seen expressed by users. My goal is to simplify how people learn and use Redux, and point them in directions that lead to better codebases. You're always welcome to use other approaches if they work better for you, but there's good reasons for all the patterns we're recommending.