Skip to main content

createSlice

A function that accepts a name, an initialState, and optionally a parent and creates a Slice object. The default parent is the rootSliceGroup.

Note that case-reducers and extraReducers are added to the slice object after it has been created. This is in contrast to the RTK createSlice where case-reducers and extraReducers are part of the configuration object.

Parameters#

createSlice accepts a single configuration object parameter, with the following options:

function createSlice({  /**   * Optional - Defines how an _actionType_ is generated given   * the _actionKey_ and the names.   */  actionTypeFormat?: 'RTK' | ActionTypeFormatFunc;
  /**   * Optional - The Slice's reducer uses, or not uses 'immer'.   */  immer?: boolean;
  /**   * The initial state returned by the Slice's reducer and selector   * when the store state has no value for this slice of state.   */  initialState: any;
  /**   * The Slice's name.   */  name: string;
  /**   * Optional - The Slice's parent.   */  parent?: SliceParent | string;})

actionTypeFormat#

Optional - Defines how an actionType is generated given the actionKey and the names.
The names is the list of the ancestors SliceGroups' name and the Slice's name.

The default format is: ${actionKey}_${[...names].reverse().join('_')}
When value is: 'RTK' it uses Redux Toolkit convention: ${names.join('/')}/${actionKey}

Otherwise the value must be a function with this signature:
(actionKey: string, names: string[]) => string

initialState#

The initial state value for this slice of state. It is returned by the Slice's reducer and selector when the store state has no value for this slice of state.

immer#

Optional - The Slice's reducer uses immer.
Default value is: true
When migrating to Slices for Redux, if you discover that some some of your existing code is not compatible with immer you can temporarily ignore it by set the immer option to false until you can fix it.
When immer is false, a warning will appear in the console.

name#

A string name for this slice of state. Also used by actionTypeFormat to generated the actionType constants.

parent#

Optional - The Slice's parent.

Default value is: rootSliceGroup
When parent is rootSliceGroup the created Slice's reducer will be added to the "root-reducer" (the reducer of the rootSliceGroup).
When parent is a SliceParent, the created Slice's reducer will be added to that parent's reducer.
When parent is a string, it represents the parent's path, and the created Slice's reducer will need to be manually added to that parent's reducer.

Return Value#

createSlice returns a Slice object.