React Advanced

0% completed

Previous
Next
Working with Store in Redux

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.

What is Store in Redux?

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.

How the Store Works with Reducers and Actions

The store interacts with the reducer to update the state based on dispatched actions. The flow is as follows:

  1. Action is dispatched via dispatch().
  2. Reducer processes the action and returns a new state.
  3. The store updates its state and notifies all subscribers.
  4. Components subscribed to the store will receive the updated state and re-render.

Example

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.

1. Set Up Redux Store

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 } });

2. Create a Reducer

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;

3. Create the Store

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.

4. Dispatch Actions to the Store

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());

5. Subscribing to Store Changes

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.

Putting It All Together

Let’s summarize the flow:

  1. Create the store: The store is initialized with the todosReducer, which defines how the state should change.
  2. Dispatch actions: Actions like addTodo(), removeTodo(), and toggleTodo() are dispatched to the store.
  3. Update the state: The store passes the dispatched action to the reducer, which calculates and returns the new state.
  4. Notify subscribers: The store updates its state and notifies all subscribers (e.g., through store.subscribe()).
  5. Access the state: You can access the updated state using store.getState().

Example of State Changes

Let’s see how the state changes as actions are dispatched:

  1. Initial state (before dispatching any action):

    []
  2. After dispatching addTodo("Learn Redux"):

    [ { id: 1, text: "Learn Redux", completed: false } ]
  3. After dispatching addTodo("Build a Redux app"):

    [ { id: 1, text: "Learn Redux", completed: false }, { id: 2, text: "Build a Redux app", completed: false } ]
  4. After dispatching toggleTodo(1):

    [ { id: 1, text: "Learn Redux", completed: true }, { id: 2, text: "Build a Redux app", completed: false } ]
  5. After dispatching removeTodo(2):

    [ { id: 1, text: "Learn Redux", completed: true } ]

Key Concepts of Redux Store

Here are some of the important aspects of the Redux store:

  1. Centralized State: The store holds the entire application state in a single JavaScript object. This makes it easy to manage and debug your application state.
  2. State Access: You can access the current state from the store using getState().
  3. State Update: The only way to change the state in the store is by dispatching actions via the dispatch() function.
  4. State Subscription: You can subscribe to the store to listen for changes using subscribe(). When the state changes, subscribers (such as components) are notified so they can re-render.
  5. Immutability: The store maintains the state in an immutable way. You never directly modify the state but always return a new state object.

Key Methods of the Store

  • 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.

.....

.....

.....

Like the course? Get enrolled and start learning!
Previous
Next