DEV Community

Discussion on: The Great Redux Toolkit Debate

Collapse
 
markerikson profile image
Mark Erikson

Good post! I'll add a couple more thoughts beyond what I said in the other thread:

createReducer/createAction

These were the first APIs we added to Redux Toolkit. createReducer really has two primary reasons for existing:

  • It originally only supported a "lookup table" parameter option for mapping action types to case reducer functions. This kind of utility was something that the community had reimplemented for themselves dozens of times (despite the basic approach being shown in the "Reducing Boilerplate" docs page since the beginning), so it was clear we needed to have some official form of that so everyone would stop recreating it.
  • By building in Immer, we guaranteed that it would "just work" correctly without anyone having to worry about it.

An additional reason is that for some reason a lot of people hate switch statements.

createAction was also something that existed in libraries like redux-actions. By writing it ourselves, we could ensure good TS typing, and build in useful bits like a "prepare callback" for defining the action payload.

Later on, we added a "builder callback" syntax for createReducer, which let us add more powerful "action matching" capabilities, as well as ensuring that the TS types for actions was correctly inferred in the provided reducer.

createSlice

I know what you mean by "defining actions first". But, what we've found is that probably 90%+ of all Redux actions are only ever handled by one slice reducer. Also, one of the most common parts of the "boilerplate" complaints was having to define action types and action creators, as well as "having" to split those across separate files like reducers.js, constants.js, and actions.js.

What really matters in Redux is the reducers. So, createSlice optimizes for that 90%+ use case - just write your case reducers, give them reasonable names, and createSlice automatically generates those action creators for you for free. The action types come along, but they're really just implementation details - the only time you need to worry about them is when you're reading the action history log in the Redux DevTools. So, way less code to write yourself, and only one file to worry about per feature.

This alone is one of the biggest savings in terms of code size and simplicity.

I'd really seriously suggest that you consider using createSlice instead of typesafe-actions + switch statements. All you have to do types-wise is supply the type of the slice state, and the type of each action payload, and all the action creators get typed correctly.

createAsyncThunk

I know you prefer sagas, but thunks have always been the most common side effects tool with Redux. As an example, see the stats on side effects libs from my "Redux Ecosystem" presentation in 2017. Declaring that we consider them to be the default was really just acknowledging what the community had already decided. And, as I said in the other comments, the fact that we provide built-in support for thunks in no way diminishes anyone's ability to use other options if they prefer.

createEntityAdapter

createEntityAdapter really just provides pre-built case reducers for you. It's up to you to decide what actions are correlated with that reducer logic, like in this example:

const booksSlice = createSlice({
  name: 'books',
  initialState: booksAdapter.getInitialState(),
  reducers: {
    // Can pass adapter functions directly as case reducers.  Because we're passing this
    // as a value, `createSlice` will auto-generate the `bookAdded` action type / creator
    bookAdded: booksAdapter.addOne,
    booksReceived(state, action) {
      // Or, call them as "mutating" helpers in a case reducer
      booksAdapter.setAll(state, action.payload.books)
    },
  },
})
Enter fullscreen mode Exit fullscreen mode

You can see some more examples of using this in action in Redux Essentials, Part 5: Performance and Normalizing Data.

RTK Query

Let me show a specific before and after comparison to illustrate the benefits. Here's the code from that same tutorial page for fetching a list of posts and managing its loading state:

// postsSlice.js
export const fetchPosts = createAsyncThunk('posts/fetchPosts', async () => {
  const response = await client.get('/fakeApi/posts')
  return response.data
})

const postsSlice = createSlice({
  name: 'posts',
  initialState,
  reducers: {
    // omit existing reducers here
  },
  extraReducers(builder) {
    builder
      .addCase(fetchPosts.pending, (state, action) => {
        state.status = 'loading'
      })
      .addCase(fetchPosts.fulfilled, (state, action) => {
        state.status = 'succeeded'
        // Add any fetched posts to the array
        state.posts = state.posts.concat(action.payload)
      })
      .addCase(fetchPosts.rejected, (state, action) => {
        state.status = 'failed'
        state.error = action.error.message
      })
  }
})

// PostsList.js
export const PostsList = () => {
  const dispatch = useDispatch()
  const posts = useSelector(selectAllPosts)

  const postStatus = useSelector(state => state.posts.status)
  const error = useSelector(state => state.posts.error)

  useEffect(() => {
    if (postStatus === 'idle') {
      dispatch(fetchPosts())
    }
  }, [postStatus, dispatch])

  // render logic here
}
Enter fullscreen mode Exit fullscreen mode

Here's that same code with RTK Query:

// apiSlice.js
// Import the RTK Query methods from the React-specific entry point
import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'

// Define our single API slice object
export const apiSlice = createApi({
  reducerPath: 'api',
  baseQuery: fetchBaseQuery({ baseUrl: '/fakeApi' }),
  endpoints: builder => ({
    getPosts: builder.query({
      query: () => '/posts'
    })
  })
})

export const { useGetPostsQuery } = apiSlice

// PostsList.js

export const PostsList = () => {
  const {
    data: posts,
    isLoading,
    isSuccess,
    isError,
    error
  } = useGetPostsQuery()

  // rendering logic here
}
Enter fullscreen mode Exit fullscreen mode

All we had to do was say "here's a URL endpoint", and we automatically got reducer logic and an auto-generated React hook that manages:

  • Initiating the request on mount
  • Making the actual request and parsing the data
  • Updating the loading state
  • Saving the data in cache
  • Selecting the data and the loading state
  • Re-rendering the component when that state changes

All of it code that you no longer have to write, and all of it correctly typed if you're using TypeScript.

API-wise, it's the exact same concept as React-Query, it's just that you define your list of known API endpoints ahead of time and get the query hooks generated for you, rather than passing fetching functions directly to the query hooks.

I will say that based on your use case of offline support, sagas are a reasonable choice here from what little I know of dealing with offline behavior.

Collapse
 
srmagura profile image
Sam Magura

Thanks for the positive response!

I also don't understand why people hate switch statements 😂. Regardless, I will reconsider using createSlice!

I like how simple your RTK Query example is, but I believe you've omitted connecting the API slice to the store. The connection to the store (especially the middleware) is what I found most intimidating.

I am curious — do createReducer or createSlice work with React's useReducer? It's nice to write reducers in the same way whether you're using Redux or useReducer. Thanks.

Collapse
 
phryneas profile image
Lenz Weber

I like how simple your RTK Query example is, but I believe you've omitted connecting the API slice to the store. The connection to the store (especially the middleware) is what I found most intimidating.

This is something you will probably do once in your application and never touch again, ever. Our recommendation is to have only one api slice (there are still mechanisms in place to split it over multiple files if it gets too big) as RTK-Q actually benefits from having everything in one slice for stuff like "automatically refetch this query when I send off that mutation successfully".

Thread Thread
 
srmagura profile image
Sam Magura

Hey Lenz, I'll respond to both you and Mark in this comment.

The number of API slices

Seems I was confused here. I thought you would create a separate API slice for each entity in your application. The word "slice" is a bit confusing since usually you subdivide your Redux state into slices for each entity (like a users slice, a customers slice, an invoices slice, .etc).

Middleware is "intimidating"

I said the inclusion of middleware was intimidating because I feel like middlewares (as a general concept) are often black boxes that the average developer does not understand. Moreover, I thought you would be adding 30+ middlewares to your store, one for each API slice. I am much less concerned now that I know there would just be 1 middleware for the 1 API slice.

I appreciate the explanation of RTK-Q and I'm going to update the description of it in my post to be more positive.

You've also convinced me to give createReducer and createSlice a shot so I'll make that update too 🙂

Thread Thread
 
phryneas profile image
Lenz Weber

Well, a slice of a cake does not mean that there is only one type of fruit on it, right?
It really just means a "piece" or "subdivision" of your store - what's in there can vary wildly, from "by-feature" slices to "per-type" slices to "everything" slices :)

I get that middleware are intimidating - but on the other hand it's how we abstract logic. Having people install saga and add a RTKQ saga would probably be even more intimidating for most ;)

Anyway, it's great you are open to all this and I can just encourage you to also experiment a bit with it - it's pretty magical, especially how much everything cuts down on TypeScript types.

Collapse
 
markerikson profile image
Mark Erikson • Edited

Hmm. Yeah, I left out the store setup piece, but that's trivial:

import postsReducer from '../features/posts/postsSlice'
import usersReducer from '../features/users/usersSlice'
import notificationsReducer from '../features/notifications/notificationsSlice'
import { apiSlice } from '../features/api/apiSlice'

export default configureStore({
  reducer: {
    posts: postsReducer,
    users: usersReducer,
    notifications: notificationsReducer,
    [apiSlice.reducerPath]: apiSlice.reducer
  },
  middleware: getDefaultMiddleware =>
    getDefaultMiddleware().concat(apiSlice.middleware)
})
Enter fullscreen mode Exit fullscreen mode

It's really only two lines: adding the slice reducer, and adding the middleware.

I'm curious, what about that aspect feels "intimidating"? I would think that the middleware setup in particular is less confusing than having to use applyMiddleware + compose with vanilla Redux.

And yes, a reducer function is just a function, and you can absolutely use reducers from createReducer/createSlice with React's useReducer hook. I've done it frequently, including in apps that weren't using a Redux store at all, because I wanted to write some complex reducers with good TS typing.