Implement Redux Store
Difficulty: MEDIUMCategory: LLDFrequency: 1Asked On 2020-08-30
Problem Statement
Design and implement a Redux-like state management system that supports predictable state updates, single source of truth, and unidirectional data flow. The system should allow components to dispatch actions, update state via reducers, and subscribe to state changes.
Functional Requirements (FR)
Single Store
•Maintain a single centralized state object.
•Ensure all state updates happen through dispatching actions.
Actions
•Represent state change intentions as plain objects: { type: string, payload?: any }.
•Provide a method to dispatch actions to the store.
Reducers
•Pure functions that take the current state and an action and return a new state.
•Support combining multiple reducers for different parts of the state.
Subscriptions
•Allow components to subscribe to state changes.
•Notify subscribers when state updates occur.
Middleware (Optional)
•Support intercepting actions before reaching reducers.
•Enable logging, async actions (thunks), or side effects.
Suggested Classes & Responsibilities
Class: Store
•Attributes:
•state → current application state
•reducers → root reducer or combined reducers
•subscribers → list of callback functions
•Methods:
•getState() → returns the current state
•dispatch(action) → updates state via reducers and notifies subscribers
•subscribe(callback) → registers a subscriber
•unsubscribe(callback) → removes a subscriber
Class: Reducer
•Method: reduce(state, action) → returns new state based on action.
•Can be composed using combineReducers for modularity.
Class: Action (Optional)
•Attributes: type, payload
•Represents a state change intention.
Class: Middleware (Optional)
•Method: handle(action, next) → intercepts action before reducers.
Data Flow (High-Level)
1.Component dispatches an action → Store.dispatch(action) invoked.
2.Store passes action to Reducer(s) → Reducer computes new state.
3.Store updates its state reference → notifies all subscribers.
4.Components react to updated state → re-render UI or perform side effects.
Key Design Considerations
•Immutability: Always return a new state object instead of mutating the current state.
•Thread-Safety: Ensure state updates are atomic (important in async scenarios).
•Efficiency: Avoid unnecessary subscriber notifications if state hasn’t changed.
•Extensibility: Support middleware, async actions, and nested reducers.
•Testability: Reducers should be pure and easily testable in isolation.