What is Redux?
- Redux is a State management pattern that helps manage application state in a predictable, centralised, and immutable way.
- Itβs commonly used in front-end frameworks like React, but it can also be applied in Swift applications using Combine.
Think of Redux like a central control system:
- There is one source of truth (a single state store).
- The only way to change state is through actions (controlled updates).
- The state updates predictably based on dispatched actions.
Redux helps manage global state changes in a predictable way by enforcing a unidirectional data flow.
π Further Reading: Redux Docs
How is Combine Used with Redux in Swift?
- Combine enhances Redux in Swift by making state updates reactive
- Instead of manually updating UI when state changes, Combine automatically propagates changes to subscribers, ensuring that views stay in sync with the state
How Redux and Combine Work Together
1οΈβ£ State is stored in a single @Published
property** inside a Store
.
2οΈβ£ Reducers update the state in response to dispatched actions.
3οΈβ£ Views subscribe to state changes** using @ObservedObject
or @StateObject
, ensuring automatic UI updates.
Key Principles of Redux
β Single Source of Truth β The entire state of the app is stored in one object.
β State is Read-Only β The only way to change state is by dispatching actions.
β Pure Functions (Reducers) β State updates are handled by pure functions called reducers.
β Unidirectional Data Flow β State flows in one direction, making it predictable.
Reference Diagram (Redux Flow)
1οΈβ£ View Dispatches an Action 2οΈβ£ Action Describes What Happened 3οΈβ£ Reducer Updates the State Based on Action 4οΈβ£ New State is stored and Used by the View
Key Takeaways
- Redux centralises state management, ensuring a single source of truth.
- Reducers handle state updates predictably through pure functions.
- State is immutable, and the only way to update it is by dispatching actions.
- Swiftβs Combine framework works well with Redux for reactive state management.
- Useful for large applications where state needs to be shared across multiple views.