New Terminology: Slices of State

Understand what slices of state mean in Redux and what role createSlice plays in that.

We'll cover the following

Redux isn’t short of terminologies. But don’t fret. I’ve got the perfect way to explain this one.

With RTK, a new terminology emerges: state slice.

What is a slice of state?

First, consider how the state of an application is generally viewed:

An application state represented as a single entity
An application state represented as a single entity

When people refer to “application state,” they mostly refer to a giant state object. The entire state of the app is represented by a single object.

However, when you write Redux applications (and if you write them well might I add), you’ll likely build your application slightly differently with pieces of state.

An application state broken down into multiple entities
An application state broken down into multiple entities

Essentially, each piece of state comes together to form the entire application state object.

Now, here’s the interesting bit.

To have a piece of state managed by Redux, you need three entities: action, reducer, and integration with the store.

If we break this down, you’ve got to:

  • Create specific action types.
  • Create action creators to generate actions of the said type.
  • Create a reducer to handle all action types.
  • Integrate the created reducer to the store mostly by using the combineReducer function.

They don’t sound like much, but between creating multiple files and thinking about action string constant, the entire process could feel “boilerplatey”.

So, what if there was a function that lets you specify what a piece of state, (a.k.a. a slice of state) should look like? What if this function also automatically created action creators and action types, so you don’t have to think about them?

Yup! You knew where I was going with this one. RTK provides just the right utility function for this: createSlice.

A slice of state is essentially a piece of your application state object, and createSlice returns an object that contains all you need to set up that slice of slate!

The creators of RTK could have chosen to call this utility createPieceOfState. However, you’d have to agree that createSlice is a shorter snazzier name!

As you may have already noticed, the concept of state slices isn’t particularly new. The moniker “slice” is perhaps new but not the underlying concept.