React Redux is a popular state management library for React applications. It helps manage and centralize your application’s state, making it easier to work with large-scale applications.
What is Redux?
Redux is a predictable state container for JavaScript apps. It:
- Stores the application’s state in a single source of truth (called the store).
- Allows components to access state and dispatch actions to update the state.
- Follows three core principles:
- Single Source of Truth: State is stored in a single object.
- State is Read-Only: State can only be changed by dispatching actions.
- Changes are Made with Pure Functions: Reducers are pure functions that specify how the state should change.
React Redux: Basics Workflow
- Store: Holds the state of the application.
- Action: Describes what you want to do (e.g., add a task, delete a user).
- Reducer: Specifies how the state changes based on the action.
- Dispatch: Sends an action to the store to update the state.
- Components: Subscribe to the store and access state via
useSelector
orconnect
.
Steps to Set Up Redux in React
1. Install Redux and React-Redux
Run the following commands:
npm install redux react-redux
2. Create a Redux Store
The store holds the global state of your application.
import { configureStore } from '@reduxjs/toolkit'; const store = configureStore({ reducer: {}, // Add your reducers here }); export default store;
3. Create a Slice (Reducers + Actions)
A slice combines a reducer and its related actions.
import { createSlice } from '@reduxjs/toolkit'; // Initial state const initialState = { count: 0, }; // Slice const counterSlice = createSlice({ name: 'counter', initialState, reducers: { increment: (state) => { state.count += 1; // Directly mutate state (thanks to Immer) }, decrement: (state) => { state.count -= 1; }, reset: (state) => { state.count = 0; }, }, }); // Export actions export const { increment, decrement, reset } = counterSlice.actions; // Export reducer export default counterSlice.reducer;
4. Add the Reducer to the Store
Update the store to include the reducer from the slice.
import { configureStore } from '@reduxjs/toolkit'; import counterReducer from './counterSlice'; const store = configureStore({ reducer: { counter: counterReducer, }, }); export default store;
5. Provide the Store to the React App
Use the <Provider>
component from react-redux
to make the store available to all components.
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') );
6. Access State in Components
Use the useSelector
and useDispatch
hooks from react-redux
to interact with the store.
Key Concepts in Redux
- Actions: Objects with a
type
field that describe what should happen.{ type: 'counter/increment' }
- Reducers: Functions that take the current state and an action, then return the updated state.
const counterReducer = (state = { count: 0 }, action) => { switch (action.type) { case 'increment': return { count: state.count + 1 }; case 'decrement': return { count: state.count - 1 }; default: return state; } };
- Store: Centralized place to hold the application state.
import { createStore } from 'redux'; const store = createStore(counterReducer);
Redux Toolkit Features
Redux Toolkit simplifies the setup process by:
- Automatically configuring the store.
- Using
createSlice
to generate reducers and actions together. - Including middleware like
redux-thunk
by default.
Best Practices
- Keep State Normalized: Use objects for complex data.
- Use Middleware: For asynchronous actions, use middleware like
redux-thunk
orredux-saga
. - Combine Slices: Split state logic into slices for modularity.
- Memoize Selectors: Use
reselect
to improve performance.