Learn Redux Toolkit – The Simplest Way to Manage State in Your JavaScript Apps

If you‘ve built any non-trivial JavaScript applications, you know that managing state can quickly become complex and error-prone. As the number of components and interactions grows, it gets harder to keep track of what state exists, what should be updating it, and how those changes flow through your app.

This is where state management libraries like Redux come to the rescue. Redux provides a centralized store that holds all the state for your application. Components can read state from the store and dispatch actions to update the state in a predictable way.

While Redux has been hugely popular and successful, one of the common complaints has been the amount of boilerplate code required to set it up and use it. You have to write action types, action creators, reducers, dispatch actions, and connect components to read state. This can feel tedious and make Redux harder to learn and adopt.

Fortunately, the Redux team recognized this pain point and created Redux Toolkit to simplify the Redux development experience. Redux Toolkit is an opinionated toolset that provides utilities to help you write Redux logic more quickly and with less code. It‘s now the official recommended approach for writing Redux applications.

In this blog post, we‘ll dive into what Redux Toolkit is, how it helps simplify Redux development, and how you can start using it in your own projects. We‘ll also walk through the main concepts covered in the excellent free Redux Toolkit course by John Smilga on the freeCodeCamp.org YouTube channel.

Let‘s get started!

What is Redux Toolkit?

As mentioned, Redux Toolkit is an opinionated toolset for efficient Redux development. It was created by the Redux team to address three main concerns:

  1. "Configuring a Redux store is too complicated"
  2. "I have to add a lot of packages to get Redux to do anything useful"
  3. "Redux requires too much boilerplate code"

Redux Toolkit provides utilities that help simplify common use cases like store setup, creating reducers and writing immutable update logic, and even creating entire "slices" of state at once. It doesn‘t fundamentally change how Redux works, but it makes it easier to use and follow best practices.

Some of the key features of Redux Toolkit include:
• configureStore(): wraps createStore to provide simplified configuration options and good defaults. It can automatically combine your slice reducers, adds whatever Redux middleware you supply, includes redux-thunk by default, and enables use of the Redux DevTools Extension.
• createReducer(): that lets you supply a lookup table of action types to case reducer functions, rather than writing switch statements.
• createAction(): generates an action creator function for the given action type string
• createSlice(): accepts an object of reducer functions, a slice name, and an initial state value, and automatically generates a slice reducer with corresponding action creators and action types.
• createAsyncThunk: accepts an action type string and a function that returns a promise, and generates a thunk that dispatches pending/fulfilled/rejected action types based on that promise
• createEntityAdapter: generates a set of reusable reducers and selectors to manage normalized data in the store
• The createSelector utility from the Reselect library, re-exported for ease of use.

Redux Toolkit is beneficial because it helps you write Redux code with less effort. It provides a more opinionated and convenient way to write Redux logic, abstracting away some of the setup process and boilerplate. Let‘s look at a quick example of how it simplifies things.

Here‘s what setting up a slice of state in plain Redux might look like:

// Action Types
const ADD_TODO = ‘ADD_TODO‘;
const TOGGLE_TODO = ‘TOGGLE_TODO‘;

// Action Creators
export function addTodo(text) {
  return { type: ADD_TODO, payload: { text } }
}

export function toggleTodo(index) {
  return { type: TOGGLE_TODO, payload: { index } }
}

// Reducer
const initialState = []

export default function todosReducer(state = initialState, action) {
  switch (action.type) {
    case ADD_TODO:
      return [...state, action.payload.text]
    case TOGGLE_TODO:
      return state.map((todo, i) => {
        if (i === action.payload.index) {
          return { ...todo, completed: !todo.completed }
        }
        return todo
      })
    default:
      return state
  }
}

Now here‘s the equivalent using Redux Toolkit:

import { createSlice } from ‘@reduxjs/toolkit‘

const todosSlice = createSlice({
  name: ‘todos‘,
  initialState: [],
  reducers: {
    addTodo: (state, action) => {
      state.push(action.payload.text)
    }, 
    toggleTodo: (state, action) => {
      const todo = state[action.payload.index]
      todo.completed = !todo.completed
    }
  }
})

export const { addTodo, toggleTodo } = todosSlice.actions

export default todosSlice.reducer

With Redux Toolkit, we can cut down a bunch of boilerplate. Creating a slice automatically generates the action types and action creators for us based on the reducers we provide. We can write the case reducers as functions inside the reducers object, and the generated reducer will handle the switching logic for us internally. We even get "mutating" immutable update logic with Immer.js.

So in summary, Redux Toolkit:
• Helps you write Redux logic with much less code
• Speeds up development by providing utilities and conventions
• Provides good defaults for store setup out of the box
• Includes popular libraries like Immer and Reselect
• Lets you focus on the core logic rather than the boilerplate

Getting Started with Redux Toolkit

Hopefully you can see how Redux Toolkit makes writing Redux logic simpler and more streamlined. So how do you get started using it in your own projects?

The recommended way to start new projects is by using the official Redux+JS or Redux+TS templates for Create React App:

# Redux + JavaScript template
npx create-react-app redux-tutorial --template redux

# Redux + TypeScript template 
npx create-react-app redux-tutorial-typescript --template redux-typescript

This will generate a new React project already set up with Redux Toolkit and React-Redux, with some example state slices and components to give you a starting point.

If you have an existing project you‘d like to use Redux Toolkit in, install it with npm or yarn:

npm install @reduxjs/toolkit react-redux

Then follow the Quick Start tutorial in the Redux Toolkit docs to set up and use the Redux store.

What You‘ll Learn In The Redux Toolkit Course

To really internalize how to use Redux Toolkit, I highly recommend watching John Smilga‘s excellent free YouTube course "Redux Toolkit Tutorial – JavaScript State Management Library" on the freeCodeCamp channel. In about 2 hours, John walks through all the key aspects of using Redux Toolkit to build a shopping cart application.

Here are some of the main topics and concepts covered in the course:

• Configuring the Redux store with configureStore
• Creating slices of state with createSlice
• Writing reducers as "mutating" update functions
• Generating action creators for slices
• Using the Redux DevTools browser extension to trace actions and state changes
• Reading data with the useSelector hook
• Dispatching actions with the useDispatch hook
• Splitting up slice logic into separate files for better organization
• Writing async logic with createAsyncThunk
• Handling promise lifecycle actions in reducers
• Memoizing expensive calculations with createSelector

The course project is a shopping cart UI where you can add/remove items, update quantities, calculate totals, and even save/load cart state from a mock API. This provides a realistic example of the types of synchronous and asynchronous logic you‘ll often need to handle in Redux apps.

By the end of the course, you‘ll have a solid foundation in the core concepts and utilities of Redux Toolkit, and be able to start applying them in your own applications. I really appreciate how John doesn‘t just show you the code, but takes time to explain the key concepts and rationale behind the approaches Redux Toolkit enables.

When Should You Use Redux Toolkit?

As a general rule of thumb, you should consider using Redux (and Redux Toolkit) when you have state that needs to be accessed by many components at different nesting levels in your component tree. If your state is only needed by one or a few closely related components, it may be simpler to manage that as local component state with useState or useReducer hooks.

Some signs that you might want to use Redux:
• You have large amounts of application state that are needed in many places in the app
• The app state is updated frequently
• The logic to update that state may be complex
• The app has a medium or large-sized codebase, and might be worked on by many people

Redux Toolkit in particular is beneficial because it provides a set of conventions and utilities that help you write Redux logic more quickly and with less code. It‘s a great choice for any size Redux project, but can be especially helpful for larger and more complex projects.

Some alternatives to Redux and Redux Toolkit for state management include:
• React‘s built-in useState and useReducer hooks for local component state
• React Context for "global" state shared by a tree of components
• Libraries like MobX, Recoil, XState, Zustand

Ultimately, the choice of state management approach depends on the specific needs and complexity of your application.

Learn More

Hopefully this post has given you a good high-level overview of what Redux Toolkit is, why it‘s useful, and how you can get started with it. To recap, Redux Toolkit is an opinionated toolset that helps simplify Redux development by providing utilities for common use cases and promoting best practices. It‘s a great choice for efficiently building Redux applications of any size.

To learn more, check out these resources:
• John Smilga‘s free Redux Toolkit course on freeCodeCamp
• The official Redux Toolkit docs and tutorials
• Redux Essentials tutorial in the Redux core docs
• React Redux docs on using Redux Toolkit with React
• Comparison of Redux Toolkit and plain Redux in the Redux FAQ

Happy coding!

Similar Posts