0
0
React Nativemobile~15 mins

Redux slices and actions in React Native - Deep Dive

Choose your learning style9 modes available
Overview - Redux slices and actions
What is it?
Redux slices and actions are ways to organize and manage the state of your app in React Native. A slice is a piece of the app's state along with the code to change it. Actions are instructions that tell the app how to update that state. Together, they help keep your app's data predictable and easy to manage.
Why it matters
Without slices and actions, managing app data can become messy and confusing, especially as the app grows. They solve the problem of keeping data changes clear and organized, so your app behaves reliably. This makes it easier to fix bugs, add features, and work with others on the same app.
Where it fits
Before learning slices and actions, you should understand basic React Native components and state. After this, you can learn about middleware, async actions, and advanced Redux patterns to handle complex app logic.
Mental Model
Core Idea
Redux slices bundle state and the ways to change it into one clear package, while actions are the messages that trigger those changes.
Think of it like...
Imagine a slice as a drawer in a filing cabinet holding related documents (state), and actions as notes you send to the drawer telling it to add, remove, or update documents.
┌─────────────┐     ┌───────────────┐
│  Redux App  │────▶│  Redux Store  │
└─────────────┘     └───────────────┘
                         │
                         ▼
               ┌───────────────────┐
               │   Redux Slice     │
               │ ┌───────────────┐ │
               │ │ State         │ │
               │ │ Actions       │ │
               │ └───────────────┘ │
               └───────────────────┘
                         ▲
                         │
                  ┌─────────────┐
                  │  Dispatch   │
                  │  Action     │
                  └─────────────┘
Build-Up - 7 Steps
1
FoundationUnderstanding Redux State Basics
🤔
Concept: Learn what state means in an app and why we need a central place to keep it.
State is the data your app uses to show things on screen or remember choices. In React Native, state can be inside components, but when apps grow, it gets hard to keep track. Redux gives a single place called the store to hold all important state, so every part of the app can access it easily.
Result
You understand that state is like the app's memory, and Redux store is a shared memory for the whole app.
Knowing why state needs central management helps you see why Redux slices and actions exist.
2
FoundationWhat Are Actions in Redux?
🤔
Concept: Actions are simple messages that say what happened and what should change in the state.
An action is a plain object with a type field describing the change, like { type: 'increment' }. When you want to change state, you send (dispatch) an action. The store listens and updates state based on the action type.
Result
You can describe changes in your app clearly by sending actions.
Understanding actions as messages separates the 'what happened' from 'how state changes', making app logic clearer.
3
IntermediateIntroducing Redux Slices
🤔Before reading on: do you think a slice is just a piece of state, or does it also include how to change that state? Commit to your answer.
Concept: A slice groups state and the functions that change it into one unit for easier management.
Instead of writing separate code for state and actions, Redux Toolkit lets you create a slice. A slice has an initial state and reducers—functions that say how to update state when actions happen. It automatically creates action creators and action types for you.
Result
You get a neat package that holds state and ways to update it, reducing boilerplate code.
Knowing slices bundle state and update logic helps you organize your app better and write less repetitive code.
4
IntermediateCreating Actions with createSlice
🤔Before reading on: do you think createSlice requires you to write action types manually, or does it generate them for you? Commit to your answer.
Concept: createSlice automatically generates action creators and action types from reducer functions.
When you define reducers inside createSlice, Redux Toolkit creates matching action creators. For example, a reducer named 'addItem' will have an action creator addItem(). You dispatch these actions to update the slice's state.
Result
You can dispatch actions easily without manually defining action types or creators.
Understanding automatic action creation saves time and reduces errors in naming or typing actions.
5
IntermediateDispatching Actions to Update State
🤔
Concept: Learn how to send actions from your components to change the Redux state.
In your React Native components, you use the dispatch function to send actions created by the slice. For example, dispatch(addItem({id: 1, name: 'Apple'})) tells Redux to run the addItem reducer and update the state.
Result
Your app's UI can trigger state changes in a clear, predictable way.
Knowing how to dispatch actions connects your UI with the Redux state, enabling interactive apps.
6
AdvancedImmutable Updates Inside Reducers
🤔Before reading on: do you think reducers can directly change state objects, or must they always return new copies? Commit to your answer.
Concept: Reducers must update state immutably, but Redux Toolkit uses Immer to let you write simpler code that looks like direct changes.
Normally, Redux reducers return new state objects without changing the old one. This avoids bugs. Redux Toolkit uses Immer behind the scenes, so you can write code that 'mutates' state, but it safely creates new copies for you.
Result
You write cleaner reducer code without worrying about breaking immutability rules.
Understanding Immer's role helps you write reducers confidently and avoid common bugs with state mutation.
7
ExpertCombining Multiple Slices in a Store
🤔Before reading on: do you think a Redux store can only have one slice, or can it combine many slices? Commit to your answer.
Concept: A Redux store can combine many slices, each managing its own part of the state, to build complex apps.
You use combineReducers to merge multiple slice reducers into one root reducer. This lets each slice handle its own state piece independently. The store then holds all slices together, and you can dispatch actions to any slice.
Result
Your app can scale by splitting state into logical slices, keeping code modular and maintainable.
Knowing how to combine slices is key to managing large apps with clear boundaries and responsibilities.
Under the Hood
Redux stores state in a single JavaScript object tree. When an action is dispatched, the store calls reducer functions with the current state and the action. Reducers return new state objects without changing the old ones. Redux Toolkit's createSlice uses Immer to let reducers write code that looks like direct mutation but actually produces new immutable state behind the scenes.
Why designed this way?
Redux was designed to make state changes predictable and traceable by enforcing immutability and pure functions. createSlice and Redux Toolkit were created later to reduce boilerplate and simplify common patterns, making Redux easier and safer to use.
┌───────────────┐
│  Dispatch     │
│  Action       │
└──────┬────────┘
       │
       ▼
┌───────────────┐
│  Root Reducer │
│ (combineReducers)│
└──────┬────────┘
       │
       ▼
┌───────────────┐     ┌───────────────┐
│  Slice A      │     │  Slice B      │
│  Reducer      │     │  Reducer      │
└──────┬────────┘     └──────┬────────┘
       │                     │
       ▼                     ▼
┌───────────────┐     ┌───────────────┐
│  State A      │     │  State B      │
└───────────────┘     └───────────────┘
       │                     │
       └────────────┬────────┘
                    ▼
             ┌───────────────┐
             │  New State    │
             └───────────────┘
Myth Busters - 4 Common Misconceptions
Quick: Do you think reducers can directly modify the existing state object? Commit to yes or no.
Common Belief:Reducers can safely change the existing state object directly to update it.
Tap to reveal reality
Reality:Reducers must never mutate the existing state directly; they must return new state objects to keep changes predictable.
Why it matters:Directly mutating state can cause bugs where the UI does not update or state changes are lost, making debugging very hard.
Quick: Do you think createSlice requires manually writing action types? Commit to yes or no.
Common Belief:You must write action type strings manually even when using createSlice.
Tap to reveal reality
Reality:createSlice automatically generates action type strings and action creators based on reducer names.
Why it matters:Manually writing action types is error-prone and verbose; automatic generation reduces mistakes and speeds development.
Quick: Do you think a Redux store can only have one slice? Commit to yes or no.
Common Belief:A Redux store can only manage one slice of state at a time.
Tap to reveal reality
Reality:A Redux store can combine many slices, each managing different parts of the state.
Why it matters:Believing this limits app design and leads to messy, monolithic state management.
Quick: Do you think dispatching an action immediately changes the state synchronously everywhere? Commit to yes or no.
Common Belief:Dispatching an action instantly updates the state and UI everywhere at the same time.
Tap to reveal reality
Reality:Dispatching triggers reducers to create new state, but React updates UI asynchronously in batches for performance.
Why it matters:Expecting immediate UI changes can cause confusion and bugs when UI lags behind state updates.
Expert Zone
1
Slices can include extraReducers to handle actions from other slices or async thunks, enabling flexible cross-slice communication.
2
Immer's proxy-based immutability means you can write 'mutating' code safely, but understanding this helps debug subtle bugs when using non-serializable data.
3
Action creators generated by createSlice include a toString method returning the action type, enabling concise usage in middleware and selectors.
When NOT to use
Redux slices and actions are less suitable for very small apps or simple state needs where React's built-in useState or Context API suffice. For complex async logic, consider middleware like Redux Saga or alternatives like Zustand or Recoil for simpler APIs.
Production Patterns
In production, slices are organized by feature or domain, combined into a root reducer. Actions are dispatched from UI or middleware. Async logic uses createAsyncThunk with slices. Selectors memoize state access. Code splitting loads slices on demand for performance.
Connections
Event-Driven Architecture
Redux actions are like events that trigger state changes, similar to event messages in distributed systems.
Understanding Redux actions as events helps grasp how apps react to user inputs and external data in a predictable flow.
Functional Programming
Reducers are pure functions that take input and return new output without side effects, a core idea in functional programming.
Knowing functional programming principles clarifies why reducers must be pure and immutable, improving code reliability.
Database Transactions
Redux state updates resemble transactions that must be atomic and consistent, ensuring app state stays valid.
Seeing Redux updates like transactions helps understand the importance of immutability and predictable state changes.
Common Pitfalls
#1Mutating state directly inside reducers.
Wrong approach:const slice = createSlice({ name: 'counter', initialState: { value: 0 }, reducers: { increment(state) { state.value += 1; // Looks like mutation but okay with Immer }, reset(state) { state = { value: 0 }; // This does NOT update state correctly } } });
Correct approach:const slice = createSlice({ name: 'counter', initialState: { value: 0 }, reducers: { increment(state) { state.value += 1; // Correct with Immer }, reset(state) { return { value: 0 }; // Return new state object } } });
Root cause:Confusing direct property changes (allowed by Immer) with reassigning the state variable itself, which does not update Redux state.
#2Manually writing action types and creators when using createSlice.
Wrong approach:const INCREMENT = 'counter/increment'; function increment() { return { type: INCREMENT }; } // Then use these manually instead of slice-generated actions
Correct approach:const slice = createSlice({ name: 'counter', initialState: { value: 0 }, reducers: { increment(state) { state.value += 1; } } }); // Use slice.actions.increment() directly
Root cause:Not leveraging createSlice automation leads to verbose, error-prone code.
#3Dispatching actions without importing or using the correct action creators.
Wrong approach:dispatch({ type: 'increment' }); // Without using slice action creators
Correct approach:dispatch(slice.actions.increment()); // Using generated action creators
Root cause:Ignoring slice-generated actions can cause typos and mismatches in action types.
Key Takeaways
Redux slices combine state and the logic to update it, making state management clearer and less repetitive.
Actions are plain messages that describe what happened, and dispatching them triggers state changes through reducers.
Reducers must update state immutably; Redux Toolkit uses Immer to let you write simpler 'mutating' code safely.
Combining multiple slices lets you organize large app state into manageable parts with clear boundaries.
Understanding these concepts helps build predictable, maintainable React Native apps that scale well.