What is Redux?
Redux is a management library often used with React applications to manage the state of an application in a predictable way. It helps store, manage and update the state of an application and enables a centralised "store" where the state resides.
Redux is particularly useful for applications where:
- Multiple components share the same state.
- State updates need to be predictable and easy to debug.
- The app grows complex with many interdependent states.
Core Principle of Redux
- Single Source of truth: The entire state of the application is stored in a single javascript object called the store.
- State is Read-Only: The state cannot be mutated directly. To update it, actions must be dispatched.
- Changes are Made with Pure Functions: Reducers are pure functions that take the current state and an action as input and return a new state.
How Redux Works
- Store: The central place where the entire state of the application is stored.
- Actions: Plain JavaScript objects that describe what should happen. For example, adding an item to a list or updating user information.
- Reducers: Pure functions that specify how the state changes in response to an action
- Dispatch: A function used to send an action to the Redux store to trigger a state change.
- Selectors: Functions that retrieve specific pieces of state from the store.
Example: Counter Application Using Redux
Step 1: Install Redux and React-Redux
Install the necessary libraries:
npm install redux react-redux
Step 2: Create Redux Setup
1.Create Actions: Define actions to describe what you want to do.
// actions.js
export const increment = () => {
return { type: 'INCREMENT' };
};
export const decrement = () => {
return { type: 'DECREMENT' };
};
2.Create Reducer: Define how the state changes based on the action.
// reducer.js
const initialState = { count: 0 };
const counterReducer = (state = initialState, action) => {
switch (action.type) {
case 'INCREMENT':
return { ...state, count: state.count + 1 };
case 'DECREMENT':
return { ...state, count: state.count - 1 };
default:
return state;
}
};
export default counterReducer;
3.Create Store: Create a centralised store using the reducer.
// store.js
import { createStore } from 'redux';
import counterReducer from './reducer';
const store = createStore(counterReducer);
export default store;
Step 3: Integrate Redux with React
- Set Up the Provider: Wrap your application with the Provider to give components access to the store.
// index.js
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import store from './store';
import App from './App';
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root')
);
- Connect Components to Redux: Use the useSelector and useDispatch hooks to interact with the Redux store.
// App.js
import React from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { increment, decrement } from './actions';
function App() {
const count = useSelector((state) => state.count);
const dispatch = useDispatch();
return (
<div>
<h1>Counter: {count}</h1>
<button onClick={() => dispatch(increment())}>Increment</button>
<button onClick={() => dispatch(decrement())}>Decrement</button>
</div>
);
}
export default App;
How the Example Works
- Initial State: The initial state (count: 0) is defined in the reducer.
- Actions: When the "Increment" button is clicked, the increment action is dispatched. Similarly, the decrement action is dispatched for the "Decrement" button. 3.Reducer: The reducer listens for the dispatched actions and updates the state accordingly.
- Store: The store holds the current state and provides it to components using the Provider.
- React Components: Components use useSelector to access the state and useDispatch to dispatch actions.
Advantages of Redux
- Centralised State: All state is stored in one place, making it easier to debug and test.
- Predictable State Updates: State changes are handled via pure functions, making them predictable.
- Improved Scalability: Redux is well-suited for large applications with complex state requirements.
- Middleware Support: Middleware like Redux Thunk or Redux Saga can handle asynchronous actions.
Conclusion
Redux provides a structured way to manage application state in large and complex React apps. By centralising the state and using actions, reducers, and a store, Redux ensures predictable and maintainable state management.
Top comments (0)