What is Redux in javascript?
2 min readSep 21, 2024
What is Redux?
Redux is a state management library often used with React (but also usable with other frameworks or vanilla JavaScript). It helps manage application state in a predictable and centralized way. Redux stores the entire state of an application in a single object, called the Store. You can check here on how Redux internally works.
Key Points:
- State Management: Redux helps manage multiple values (states) centrally rather than in individual components.
- Global Access: The Redux store is accessible throughout the application, making state available to all components.
- Two-Way Communication: Components can read from the store and dispatch actions to modify the state.
Why Redux?
Challenges with React’s Built-in State Management:
- Component Scope: In React, the state is local to each component. State managed within one component is not directly accessible to other components.
- Prop Drilling: Passing data through props can become cumbersome as your component tree grows. This process is known as “prop drilling.”
- Unidirectional Data Flow: React components follow a unidirectional data flow. Parent components pass data down to child components, but child components cannot directly modify data in parent components.
- Complex Data Management: In large applications with many components, managing state across different parts of the app can become challenging.
How Redux Addresses These Challenges:
- Centralized State: Redux maintains the state in a single global store, which is accessible by any component. This eliminates the need for prop drilling.
- Global State Access: Any component can access the global state and dispatch actions to update it, providing a more streamlined way to manage shared data.
- Predictable State Updates: Redux uses a predictable state update mechanism through actions and reducers, making state changes more transparent and easier to debug.
- Middleware for Side Effects: Redux middleware (like Redux Thunk or Redux Saga) can handle asynchronous actions and side effects, helping manage more complex scenarios.
Basic Redux Workflow
- Store: Contains the application state and provides methods to access it.
- Actions: Plain objects that describe what happened and can carry data (payload) to be processed.
- Reducers: Functions that specify how the state changes in response to actions. They take the current state and an action, and return a new state.
- Dispatch: A function used to send actions to the store to trigger state updates.
Example Redux Flow
- Define Actions: Describe the changes you want to make.
- Create Reducers: Define how these actions update the state.
- Configure Store: Combine reducers and set up the store.
- Connect Components: Use the Redux store in React components to read state and dispatch actions
- useSelector() hook for reading
- dispatch() action to update state value
You can check here on how Redux internally works.
Happy Learning!!