Redux & Redux Toolkit
/Intermediate
createAction()
Definition
A utility function from RTK that takes an action type string and returns an action creator function for that type.
Explain Like I'm New
While `createSlice` is the standard, sometimes you need to create a standalone action that isn't tied to a specific slice. `createAction` does this in one line.
Real World Example
Creating a global `APP_RESET` action. You dispatch it when the user clicks 'Logout', and 5 different slices listen for this standalone action to clear their individual states.
Common Use Cases
- •Creating standalone actions
- •Cross-slice communication
Interactive Example
import { createAction, createSlice } from '@reduxjs/toolkit'; // 1. Create a standalone global action export const resetApp = createAction('app/reset'); // 2. A slice can listen to it using extraReducers const userSlice = createSlice({ name: 'user', initialState: { name: 'John' }, reducers: {}, extraReducers: (builder) => { // When the global reset action is dispatched anywhere in the app, do this: builder.addCase(resetApp, (state) => { state.name = null; }); } });
Interview Questions
basic
- If you create an action using `const login = createAction('LOGIN')`, how do you dispatch it?
intermediate
- How does a `createSlice` listen for an action created by `createAction`?