0% completed
In this lesson, we will be studying the final piece of Redux's architecture. This final piece is the store and by the end of this lesson, you will have learned about its importance and how to use it in your React app.
The store is a central object that holds the state of the entire application. It is the source of truth for your application's state, and all updates to the state are made via dispatching actions to the store. The store provides methods to get the current state, dispatch actions, and subscribe to state changes.
The Redux store is what makes Redux work, as it coordinates the state management by interacting with reducers and actions. The store connects your components (or views) to the state of your app, ensuring that the state is predictable, manageable, and traceable.
The store interacts with the reducer to update the state based on dispatched actions. The flow is as follows:
dispatch()
.To understand how to use the store, we'll continue with the to-do app example, where we have to manage a list of to-dos. We’ll demonstrate how to create a store and interact with it by dispatching actions.
First, we’ll create the Redux store, add reducers, and dispatch actions.
// actions.js export const addTodo = (text) => ({ type: 'ADD_TODO', payload: { text, completed: false } }); export const removeTodo = (id) => ({ type: 'REMOVE_TODO', payload: { id } }); export const toggleTodo = (id) => ({ type: 'TOGGLE_TODO', payload: { id } });
We’ll use the todosReducer
from the previous example, which manages the to-do list state.
// reducers.js const initialState = []; const todosReducer = (state = initialState, action) => { switch (action.type) { case 'ADD_TODO': return [ ...state, { id: Date.now(), text: action.payload.text, completed: action.payload.completed }; case 'REMOVE_TODO': return state.filter(todo => todo.id !== action.payload.id); case 'TOGGLE_TODO': return state.map(todo => todo.id === action.payload.id ? { ...todo, completed: !todo.completed } : todo ); default: return state; } }; export default todosReducer;
Next, we will create the Redux store using the createStore
function from Redux. The store is initialized with the reducer (todosReducer
), which will handle all actions related to the to-do list.
// store.js import { createStore } from 'redux'; import todosReducer from './reducers'; // Create the store with the todosReducer const store = createStore(todosReducer); export default store;
At this point, we have a store that manages the to-do list. It uses the todosReducer
to update the state when actions like ADD_TODO
, REMOVE_TODO
, and TOGGLE_TODO
are dispatched.
Once the store is created, we can interact with it by dispatching actions. For example, we can add a new to-do, toggle its completion, or remove a to-do item.
import store from './store'; import { addTodo, toggleTodo, removeTodo } from './actions'; // Dispatching actions store.dispatch(addTodo("Learn Redux")); store.dispatch(addTodo("Build a Redux app")); store.dispatch(toggleTodo(1)); // Toggle the completion status of the first to-do store.dispatch(removeTodo(2)); // Remove the second to-do // Getting the current state console.log(store.getState());
You can subscribe to the store to listen for changes in the state. This is often done in React components or other parts of your application that need to react to state updates.
store.subscribe(() => { console.log("State updated:", store.getState()); });
Whenever an action is dispatched, the store will notify the subscriber, which in this case is a console.log
statement that prints the updated state.
Let’s summarize the flow:
todosReducer
, which defines how the state should change.addTodo()
, removeTodo()
, and toggleTodo()
are dispatched to the store.store.subscribe()
).store.getState()
.Let’s see how the state changes as actions are dispatched:
Initial state (before dispatching any action):
[]
After dispatching addTodo("Learn Redux")
:
[ { id: 1, text: "Learn Redux", completed: false } ]
After dispatching addTodo("Build a Redux app")
:
[ { id: 1, text: "Learn Redux", completed: false }, { id: 2, text: "Build a Redux app", completed: false } ]
After dispatching toggleTodo(1)
:
[ { id: 1, text: "Learn Redux", completed: true }, { id: 2, text: "Build a Redux app", completed: false } ]
After dispatching removeTodo(2)
:
[ { id: 1, text: "Learn Redux", completed: true } ]
Here are some of the important aspects of the Redux store:
getState()
.dispatch()
function.subscribe()
. When the state changes, subscribers (such as components) are notified so they can re-render.getState()
: This method retrieves the current state of the application.dispatch(action)
: This method is used to dispatch an action to the store. Dispatching an action will trigger the reducer, which will calculate the new state.subscribe(listener)
: This method subscribes to the store to be notified whenever the state changes. The listener
is a callback function that is executed every time the state updates.replaceReducer(nextReducer)
: This method allows you to replace the reducer function used by the store (useful in advanced use cases like code splitting).By using the store, Redux ensures that the application’s state is predictable and easily managed, especially in larger applications where state management can otherwise become complex.
.....
.....
.....