Skip to content

v2.0.0

Compare
Choose a tag to compare
@markerikson markerikson released this 04 Dec 14:10
· 1363 commits to master since this release

This major release :

  • Removes the deprecated object syntax from createSlice and createReducer
  • Removes other deprecated options
  • Updates the middleware and enhancers options of configureStore to require callbacks
  • Updates the packaging for better ESM/CJS compatibility and modernizes the build output
  • Includes all changes to Redux core 5.0, Reselect 5.0, and Redux Thunk 3.0
  • Updates RTKQ default subscription behavior
  • Adds a new combineSlices method with support for lazy-loading slice reducers
  • Adds a new "dynamic middleware" middleware with support for adding middleware at runtime
  • Adds a new callback syntax to createSlice.reducers, with optional support for defining thunks inside of createSlice
  • Adds the autoBatchEnhancer to configureStore by default
  • Has many additional TS tweaks and improvements

This release has breaking changes. (Note: v2.0.1 was released with a couple hotfixes for Reselect and Redux Thunk right as this was being finalized.)

This release is part of a wave of major versions of all the Redux packages: Redux Toolkit 2.0, Redux core 5.0, React-Redux 9.0, Reselect 5.0, and Redux Thunk 3.0.

For full details on all of the breaking changes and other significant changes to all of those packages, see the "Migrating to RTK 2.0 and Redux 5.0" migration guide in the Redux docs.

Note

The Redux core, Reselect, and Redux Thunk packages are included as part of Redux Toolkit, and RTK users do not need to manually upgrade them - you'll get them as part of the upgrade to RTK 2.0. (If you're not using Redux Toolkit yet, please start migrating your existing legacy Redux code to use Redux Toolkit today!)

# RTK
npm install @reduxjs/toolkit
yarn add @reduxjs/toolkit

Changelog

Object syntax for createSlice.extraReducers and createReducer removed

RTK's createReducer API was originally designed to accept a lookup table of action type strings to case reducers, like { "ADD_TODO": (state, action) => {} }. We later added the "builder callback" form to allow more flexibility in adding "matchers" and a default handler, and did the same for createSlice.extraReducers.

We have removed the "object" form for both createReducer and createSlice.extraReducers in RTK 2.0, as the builder callback form is effectively the same number of lines of code, and works much better with TypeScript.

As an example, this:

const todoAdded = createAction('todos/todoAdded')

createReducer(initialState, {
  [todoAdded]: (state, action) => {},
})

createSlice({
  name,
  initialState,
  reducers: {
    /* case reducers here */
  },
  extraReducers: {
    [todoAdded]: (state, action) => {},
  },
})

should be migrated to:

createReducer(initialState, (builder) => {
  builder.addCase(todoAdded, (state, action) => {})
})

createSlice({
  name,
  initialState,
  reducers: {
    /* case reducers here */
  },
  extraReducers: (builder) => {
    builder.addCase(todoAdded, (state, action) => {})
  },
})
Codemods

To simplify upgrading codebases, we've published a set of codemods that will automatically transform the deprecated "object" syntax into the equivalent "builder" syntax.

The codemods package is available on NPM as @reduxjs/rtk-codemods. More details are available here.

To run the codemods against your codebase, run npx @reduxjs/rtk-codemods <TRANSFORM NAME> path/of/files/ or/some**/*glob.js.

Examples:

npx @reduxjs/rtk-codemods createReducerBuilder ./src

npx @reduxjs/rtk-codemods createSliceBuilder ./packages/my-app/**/*.ts

We also recommend re-running Prettier on the codebase before committing the changes.

These codemods should work, but we would greatly appreciate feedback from more real-world codebases!

configureStore Options Changes

configureStore.middleware must be a callback

Since the beginning, configureStore has accepted a direct array value as the middleware option. However, providing an array directly prevents configureStore from calling getDefaultMiddleware(). So, middleware: [myMiddleware] means there is no thunk middleware added (or any of the dev-mode checks).

This is a footgun, and we've had numerous users accidentally do this and cause their apps to fail because the default middleware never got configured.

As a result, we've now made the middleware only accept the callback form. If for some reason you still want to replace all of the built-in middleware, do so by returning an array from the callback:

const store = configureStore({
  reducer,
  middleware: (getDefaultMiddleware) => {
    // WARNING: this means that _none_ of the default middleware are added!
    return [myMiddleware]
    // or for TS users, use:
    // return new Tuple(myMiddleware)
  },
})

But note that we consistently recommend not replacing the default middleware entirely, and that you should use return getDefaultMiddleware().concat(myMiddleware).

configureStore.enhancers must be a callback

Similarly to configureStore.middleware, the enhancers field must also be a callback, for the same reasons.

The callback will receive a getDefaultEnhancers function that can be used to customise the batching enhancer that's now included by default.

For example:

const store = configureStore({
  reducer,
  enhancers: (getDefaultEnhancers) => {
    return getDefaultEnhancers({
      autoBatch: { type: 'tick' },
    }).concat(myEnhancer)
  },
})

It's important to note that the result of getDefaultEnhancers will also contain the middleware enhancer created with any configured/default middleware. To help prevent mistakes, configureStore will log an error to console if middleware was provided and the middleware enhancer wasn't included in the callback result.

const store = configureStore({
  reducer,
  enhancers: (getDefaultEnhancers) => {
    return [myEnhancer] // we've lost the  middleware here
    // instead:
    return getDefaultEnhancers().concat(myEnhancer)
  },
})

Also, note that if you supply the enhancers field, it must come after the middleware field in order for TS inference to work properly.

Standalone getDefaultMiddleware and getType removed

The standalone version of getDefaultMiddleware has been deprecated since v1.6.1, and has now been removed. Use the function passed to the middleware callback instead, which has the correct types.

We have also removed the getType export, which was used to extract a type string from action creators made with createAction. Instead, use the static property actionCreator.type.

RTK Query behaviour changes

We've had a number of reports where RTK Query had issues around usage of dispatch(endpoint.initiate(arg, {subscription: false})). There were also reports that multiple triggered lazy queries were resolving the promises at the wrong time. Both of these had the same underlying issue, which was that RTKQ wasn't tracking cache entries in these cases (intentionally). We've reworked the logic to always track cache entries (and remove them as needed), which should resolve those behavior issues.

We also have had issues raised about trying to run multiple mutations in a row and how tag invalidation behaves. RTKQ now has internal logic to delay tag invalidation briefly, to allow multiple invalidations to get handled together. This is controlled by a new invalidationBehavior: 'immediate' | 'delayed' flag on createApi. The new default behavior is 'delayed'. Set it to 'immediate' to revert to the behavior in RTK 1.9.

In RTK 1.9, we reworked RTK Query's internals to keep most of the subscription status inside the RTKQ middleware. The values are still synced to the Redux store state, but this is primarily for display by the Redux DevTools "RTK Query" panel. Related to the cache entry changes above, we've optimized how often those values get synced to the Redux state for perf.

ESM/CJS Package Compatibility

The biggest theme of the Redux v5 and RTK 2.0 releases is trying to get "true" ESM package publishing compatibility in place, while still supporting CJS in the published package.

The primary build artifact is now an ESM file, dist/redux-toolkit.modern.mjs. Most build tools should pick this up. There's also a CJS artifact, and a second copy of the ESM file named redux-toolkit.legacy-esm.js to support Webpack 4 (which does not recognize the exports field in package.json). Additionally, all of the build artifacts now live under ./dist/ in the published package.

Modernized Build Output

We now publish modern JS syntax targeting ES2020, including optional chaining, object spread, and other modern syntax. If you need to target older browsers, please transpile the packages yourself (or use the legacy-esm build artifact for ES2017).

Build Tooling

We're now building the package using https://github.com/egoist/tsup. We also now include sourcemaps for the ESM and CJS artifacts.

Dropping UMD Builds

Redux has always shipped with UMD build artifacts. These are primarily meant for direct import as script tags, such as in a CodePen or a no-bundler build environment.

We've dropped those build artifacts from the published package, on the grounds that the use cases seem pretty rare today.

There's now a redux-toolkit.browser.mjs file in the package that can be loaded from a CDN like Unpkg.

If you have strong use cases for us continuing to include UMD build artifacts, please let us know!

Dependency Updates

Redux Libraries

RTK now depends on Redux core 5.0, Reselect 5.0, and Redux Thunk 3.0. See the linked release notes for those libraries, as each of them has additional breaking changes. The "Migrating to RTK 2.0 and Redux 5.0" docs page also covers the combined changes in one page

Immer 10

RTK now also depends on Immer 10.0, which has several major improvements and updates:

  • Much faster update perf
  • Much smaller bundle size
  • Better ESM/CJS package formatting
  • No default export
  • No ES5 fallback

We've also removed the prior call to automatically enable the Immer ES5 fallback mode any time RTK was loaded.

Other Changes

Bundle Size Optimizations

Redux 4.1.0 optimized its bundle size by extracting error message strings out of production builds, based on React's approach. We've applied the same technique to RTK. This saves about 1000 bytes from prod bundles (actual benefits will depend on which imports are being used).

We also noted that ESBuild does not deduplicate imports when it bundles source files, and this was causing RTK Query's bundle to contain a dozen references to import { } from "@reduxjs/toolkit", including some of the same methods. Manually deduplicating those saves about 600 bytes off the production RTKQ artifact.

reactHooksModule custom hook configuration

Previously, custom versions of React Redux's hooks (useSelector, useDispatch, and useStore) could be passed separately to reactHooksModule, usually to enable using a different context to the default ReactReduxContext.

In practicality, the react hooks module needs all three of these hooks to be provided, and it became an easy mistake to only pass useSelector and useDispatch, without useStore.

The module has now moved all three of these under the same configuration key, and will check that all three are provided if the key is present.

// previously
const customCreateApi = buildCreateApi(
  coreModule(),
  reactHooksModule({
    useDispatch: createDispatchHook(MyContext),
    useSelector: createSelectorHook(MyContext),
    useStore: createStoreHook(MyContext),
  })
)

// now
const customCreateApi = buildCreateApi(
  coreModule(),
  reactHooksModule({
    hooks: {
      useDispatch: createDispatchHook(MyContext),
      useSelector: createSelectorHook(MyContext),
      useStore: createStoreHook(MyContext),
    },
  })
)

Deprecated Options Removed

Several other options were previously marked as deprecated, and have been removed. We've also removed polyfills like the AbortController polyfill.

TypeScript Changes

configureStore field order for middleware matters

If you are passing both the middleware and enhancers fields to configureStore, the middleware field must come first in order for internal TS inference to work properly.

Non-default middleware/enhancers must use Tuple

We've seen many cases where users passing the middleware parameter to configureStore have tried spreading the array returned by getDefaultMiddleware(), or passed an alternate plain array. This unfortunately loses the exact TS types from the individual middleware, and often causes TS problems down the road (such as dispatch being typed as Dispatch<AnyAction> and not knowing about thunks).

getDefaultMiddleware() already used an internal MiddlewareArray class, an Array subclass that had strongly typed .concat/prepend() methods to correctly capture and retain the middleware types.

We've renamed that type to Tuple, and configureStore's TS types now require that you must use Tuple if you want to pass your own array of middleware:

import { configureStore, Tuple } from '@reduxjs/toolkit'

configureStore({
  reducer: rootReducer,
  middleware: (getDefaultMiddleware) => new Tuple(additionalMiddleware, logger),
})

(Note that this has no effect if you're using RTK with plain JS, and you could still pass a plain array here.)

This same restriction applies to the enhancers field.

Entity adapter type updates

createEntityAdapter now has an Id generic argument, which will be used to strongly type the item IDs anywhere those are exposed. Previously, the ID field type was always string | number. TS will now try to infer the exact type from either the .id field of your entity type, or the selectId return type. You could also fall back to passing that generic type directly. If you use the EntityState<Data, Id> type directly, you must supply both generic arguments!

The .entities lookup table is now defined to use a standard TS Record<Id, MyEntityType>, which assumes that each item lookup exists by default. Previously, it used a Dictionary<MyEntityType> type, which assumed the result was MyEntityType | undefined. The Dictionary type has been removed.

If you prefer to assume that the lookups might be undefined, use TypeScript's noUncheckedIndexedAccess configuration option to control that.

New Features

These features are new in Redux Toolkit 2.0, and help cover additional use cases that we've seen users ask for in the ecosystem.

combineSlices API with slice reducer injection for code-splitting

The Redux core has always included combineReducers, which takes an object full of "slice reducer" functions and generates a reducer that calls those slice reducers. RTK's createSlice generates slice reducers + associated action creators, and we've taught the pattern of exporting individual action creators as named exports and the slice reducer as a default export. Meanwhile, we've never had official support for lazy-loading reducers, although we've had sample code for some "reducer injection" patterns in our docs.

This release includes a new combineSlices API that is designed to enable lazy-loading of reducers at runtime. It accepts individual slices or an object full of slices as arguments, and automatically calls combineReducers using the sliceObject.name field as the key for each state field. The generated reducer function has an additional .inject() method attached that can be used to dynamically inject additional slices at runtime. It also includes a .withLazyLoadedSlices() method that can be used to generate TS types for reducers that will be added later. See #2776 for the original discussion around this idea.

For now, we are not building this into configureStore, so you'll need to call const rootReducer = combineSlices(.....) yourself and pass that to configureStore({reducer: rootReducer}).

Basic usage: a mixture of slices and standalone reducers passed to combineSlices

const stringSlice = createSlice({
  name: 'string',
  initialState: '',
  reducers: {},
})

const numberSlice = createSlice({
  name: 'number',
  initialState: 0,
  reducers: {},
})

const booleanReducer = createReducer(false, () => {})

const api = createApi(/*  */)

const combinedReducer = combineSlices(
  stringSlice,
  {
    num: numberSlice.reducer,
    boolean: booleanReducer,
  },
  api
)
expect(combinedReducer(undefined, dummyAction())).toEqual({
  string: stringSlice.getInitialState(),
  num: numberSlice.getInitialState(),
  boolean: booleanReducer.getInitialState(),
  api: api.reducer.getInitialState(),
})

Basic slice reducer injection

// Create a reducer with a TS type that knows `numberSlice` will be injected
const combinedReducer =
  combineSlices(stringSlice).withLazyLoadedSlices<
    WithSlice<typeof numberSlice>
  >()

// `state.number` doesn't exist initially
expect(combinedReducer(undefined, dummyAction()).number).toBe(undefined)

// Create a version of the reducer with `numberSlice` injected (mainly useful for types)
const injectedReducer = combinedReducer.inject(numberSlice)

// `state.number` now exists, and injectedReducer's type no longer marks it as optional
expect(injectedReducer(undefined, dummyAction()).number).toBe(
  numberSlice.getInitialState()
)

// original reducer has also been changed (type is still optional)
expect(combinedReducer(undefined, dummyAction()).number).toBe(
  numberSlice.getInitialState()
)

selectors field in createSlice

The existing createSlice API now has support for defining selectors directly as part of the slice. By default, these will be generated with the assumption that the slice is mounted in the root state using slice.name as the field, such as name: "todos" -> rootState.todos. Additionally, there's now a slice.selectSlice method that does that default root state lookup.

You can call sliceObject.getSelectors(selectSliceState) to generate the selectors with an alternate location, similar to how entityAdapter.getSelectors() works.

const slice = createSlice({
  name: 'counter',
  initialState: 42,
  reducers: {},
  selectors: {
    selectSlice: (state) => state,
    selectMultiple: (state, multiplier: number) => state * multiplier,
  },
})

// Basic usage
const testState = {
  [slice.name]: slice.getInitialState(),
}
const { selectSlice, selectMultiple } = slice.selectors
expect(selectSlice(testState)).toBe(slice.getInitialState())
expect(selectMultiple(testState, 2)).toBe(slice.getInitialState() * 2)

// Usage with the slice reducer mounted under a different key
const customState = {
  number: slice.getInitialState(),
}
const { selectSlice, selectMultiple } = slice.getSelectors(
  (state: typeof customState) => state.number
)
expect(selectSlice(customState)).toBe(slice.getInitialState())
expect(selectMultiple(customState, 2)).toBe(slice.getInitialState() * 2)

createSlice.reducers callback syntax and thunk support

One of the oldest feature requests we've had is the ability to declare thunks directly inside of createSlice. Until now, you've always had to declare them separately, give the thunk a string action prefix, and handle the actions via createSlice.extraReducers:

// Declare the thunk separately
const fetchUserById = createAsyncThunk(
  'users/fetchByIdStatus',
  async (userId: number, thunkAPI) => {
    const response = await userAPI.fetchById(userId)
    return response.data
  }
)

const usersSlice = createSlice({
  name: 'users',
  initialState,
  reducers: {
    // standard reducer logic, with auto-generated action types per reducer
  },
  extraReducers: (builder) => {
    // Add reducers for additional action types here, and handle loading state as needed
    builder.addCase(fetchUserById.fulfilled, (state, action) => {
      state.entities.push(action.payload)
    })
  },
})

Many users have told us that this separation feels awkward.

We've wanted to include a way to define thunks directly inside of createSlice, and have played around with various prototypes. There were always two major blocking issues, and a secondary concern:

  1. It wasn't clear what the syntax for declaring a thunk inside should look like.
  2. Thunks have access to getState and dispatch, but the RootState and AppDispatch types are normally inferred from the store, which in turn infers it from the slice state types. Declaring thunks inside createSlice would cause circular type inference errors, as the store needs the slice types but the slice needs the store types. We weren't willing to ship an API that would work okay for our JS users but not for our TS users, especially since we want people to use TS with RTK.
  3. You can't do synchronous conditional imports in ES modules, and there's no good way to make the createAsyncThunk import optional. Either createSlice always depends on it (and adds that to the bundle size), or it can't use createAsyncThunk at all.

We've settled on these compromises:

  • In order to create async thunks with createSlice, you specifically need to set up a custom version of createSlice that has access to createAsyncThunk.
  • You can declare thunks inside of createSlice.reducers, by using a "creator callback" syntax for the reducers field that is similar to the build callback syntax in RTK Query's createApi (using typed functions to create fields in an object). Doing this does look a bit different than the existing "object" syntax for the reducers field, but is still fairly similar.
  • You can customize some of the types for thunks inside of createSlice, but you cannot customize the state or dispatch types. If those are needed, you can manually do an as cast, like getState() as RootState.

In practice, we hope these are reasonable tradeoffs. Creating thunks inside of createSlice has been widely asked for, so we think it's an API that will see usage. If the TS customization options are a limitation, you can still declare thunks outside of createSlice as always, and most async thunks don't need dispatch or getState - they just fetch data and return. And finally, setting up a custom createSlice allows you to opt into createAsyncThunk being included in your bundle size (though it may already be included if used directly or as part of RTK Query - in either of these cases there's no additional bundle size).

Here's what the new callback syntax looks like:

const createSliceWithThunks = buildCreateSlice({
  creators: { asyncThunk: asyncThunkCreator },
})

const todosSlice = createSliceWithThunks({
  name: 'todos',
  initialState: {
    loading: false,
    todos: [],
    error: null,
  } as TodoState,
  reducers: (create) => ({
    // A normal "case reducer", same as always
    deleteTodo: create.reducer((state, action: PayloadAction<number>) => {
      state.todos.splice(action.payload, 1)
    }),
    // A case reducer with a "prepare callback" to customize the action
    addTodo: create.preparedReducer(
      (text: string) => {
        const id = nanoid()
        return { payload: { id, text } }
      },
      // action type is inferred from prepare callback
      (state, action) => {
        state.todos.push(action.payload)
      }
    ),
    // An async thunk
    fetchTodo: create.asyncThunk(
      // Async payload function as the first argument
      async (id: string, thunkApi) => {
        const res = await fetch(`myApi/todos?id=${id}`)
        return (await res.json()) as Item
      },
      // An object containing `{pending?, rejected?, fulfilled?, settled?, options?}` second
      {
        pending: (state) => {
          state.loading = true
        },
        rejected: (state, action) => {
          state.error = action.payload ?? action.error
        },
        fulfilled: (state, action) => {
          state.todos.push(action.payload)
        },
        // settled is called for both rejected and fulfilled actions
        settled: (state, action) => {
          state.loading = false
        },
      }
    ),
  }),
})

// `addTodo` and `deleteTodo` are normal action creators.
// `fetchTodo` is the async thunk
export const { addTodo, deleteTodo, fetchTodo } = todosSlice.actions

Codemod

Using the new callback syntax is entirely optional (the object syntax is still standard), but an existing slice would need to be converted before it can take advantage of the new capabilities this syntax provides. To make this easier, a codemod is provided.

npx @reduxjs/rtk-codemods createSliceReducerBuilder ./src/features/todos/slice.ts

"Dynamic middleware" middleware

A Redux store's middleware pipeline is fixed at store creation time and can't be changed later. We have seen ecosystem libraries that tried to allow dynamically adding and removing middleware, potentially useful for things like code splitting.

This is a relatively niche use case, but we've built our own version of a "dynamic middleware" middleware. Add it to the Redux store at setup time, and it lets you add middleware later at runtime. It also comes with a React hook integration that will automatically add a middleware to the store and return the updated dispatch method..

import { createDynamicMiddleware, configureStore } from '@reduxjs/toolkit'

const dynamicMiddleware = createDynamicMiddleware()

const store = configureStore({
  reducer: {
    todos: todosReducer,
  },
  middleware: (getDefaultMiddleware) =>
    getDefaultMiddleware().prepend(dynamicMiddleware.middleware),
})

// later
dynamicMiddleware.addMiddleware(someOtherMiddleware)

configureStore adds autoBatchEnhancer by default

In v1.9.0, we added a new autoBatchEnhancer that delays notifying subscribers briefly when multiple "low-priority" actions are dispatched in a row. This improves perf, as UI updates are typically the most expensive part of the update process. RTK Query marks most of its own internal actions as "low-pri" by default, but you have to have the autoBatchEnhancer added to the store to benefit from that.

We've updated configureStore to add the autoBatchEnhancer to the store setup by default, so that users can benefit from the improved perf without needing to manually tweak the store config themselves.

entityAdapter.getSelectors accepts a createSelector function

entityAdapter.getSelectors() now accepts an options object as its second argument. This allows you to pass in your own preferred createSelector method, which will be used to memoize the generated selectors. This could be useful if you want to use one of Reselect's new alternate memoizers, or some other memoization library with an equivalent signature.

Next.js Setup Guide

We now have a docs page that covers how to set up Redux properly with Next.js. We've seen a lot of questions around using Redux, Next, and the App Router together, and this guide should help provide advice.

(At this time, the Next.js with-redux example is still showing outdated patterns - we're going to file a PR shortly to update that to match our docs guide.)

What's Changed

Full Changelog: v1.9.3...v2.0.0