Redux & State Management Basics

Let’s make sharing state easy!

Photo by Ferenc Almasi on Unsplash

Redux is a state management library that is used to manage the state of an application. It provides a predictable and centralized way to manage the state of an application, making it easier to debug and reason about. Redux is not a standalone library; it is often used with React and other libraries to build complex applications. In this article, we will explore Redux and how it can help manage state in a React application.

What is State Management?

In software development, state refers to the condition or status of an application at a particular point in time. State management involves handling and manipulating this state throughout the life cycle of an application. Managing state is crucial for building complex applications because it enables the application to respond to user input and produce the correct output.

In a React application, state management can become challenging as the application grows more complex. Managing state with React’s built-in state management system can become cumbersome, especially when passing state between different components. Redux solves this problem by providing a centralized state management system that can be accessed by all components.

What is Redux?

Redux is a state management library that was inspired by Flux, a pattern for managing state in web applications. Redux is based on three fundamental principles: a single source of truth, state is read-only, and changes are made with pure functions. Let’s explore these principles in more detail.

Single Source of Truth

In a Redux application, there is a single source of truth for the entire application. This source of truth is called the store and is an object that holds the entire state of the application. All components in the application can access this state through the store, and changes to the state can be made through actions.

State is Read-only

The state in a Redux application is read-only, which means that components cannot modify the state directly. Instead, changes to the state are made through actions. An action is an object that describes the change that needs to be made to the state. The store receives this action and updates the state accordingly.

Changes are Made with Pure Functions

Redux follows the principles of functional programming, and all changes to the state are made with pure functions. Pure functions take an input and return an output without affecting anything outside the function. In Redux, these functions are called reducers, and they receive the current state and an action and return the new state.

Benefits of Using Redux for State Management

There are several benefits to using Redux for state management in a React application. These benefits include:

  1. Centralized State Management: Redux provides a centralized state management system that can be accessed by all components. This makes it easier to manage state in large applications.
  2. Predictable State Changes: Redux follows a strict set of rules for how state changes are made, which makes it easier to debug and reason about state changes.
  3. Time Travel Debugging: Redux allows you to track the changes to the state over time, making it easier to debug and understand how the application is behaving.
  4. Reusable Code: Redux code is reusable, which means that it can be used in different applications without having to rewrite the same code.

Let’s look at an example:

Suppose we are building a simple e-commerce website that allows users to add items to their cart and checkout. We want to use Redux to manage the state of the cart.

Step 1: Set up the Redux Store
First, we need to set up the Redux store. We can use the createStore function from the redux library to create the store. We also need to define a reducer function that will handle changes to the cart state.

import { createStore } from 'redux';

const initialState = {
cartItems: [],
};

function cartReducer(state = initialState, action) {
switch (action.type) {
case 'ADD_TO_CART':
return {
...state,
cartItems: [...state.cartItems, action.payload],
};
case 'REMOVE_FROM_CART':
return {
...state,
cartItems: state.cartItems.filter(item => item.id !== action.payload),
};
default:
return state;
}
}

const store = createStore(cartReducer);

In this code, we define an initial state with an empty cart. The cartReducer function handles two actions: ADD_TO_CART and REMOVE_FROM_CART. When the ADD_TO_CART action is dispatched, it adds the item to the cartItems array in the state. When the REMOVE_FROM_CART action is dispatched, it removes the item with the specified ID from the cartItems array.

Step 2: Connect the Component to the Store

import { useSelector } from 'react-redux';

function Cart() {
const cartItems = useSelector(state => state.cartItems);

return (
<div>
<h2>Cart</h2>
<ul>
{cartItems.map(item => (
<li key={item.id}>
{item.name} - ${item.price}
<button onClick={() => dispatch({ type: 'REMOVE_FROM_CART', payload: item.id })}>Remove</button>
</li>
))}
</ul>
</div>
);
}

In this code, we use the useSelector hook to access the cartItems array from the store. We then display the items in a list and provide a button to remove items from the cart. When the button is clicked, we dispatch the REMOVE_FROM_CART action with the item ID as the payload.

Step 3: Dispatch Actions to the Store
Finally, we need to dispatch actions to the store to add or remove items from the cart. We can use the useDispatch hook from the react-redux library to dispatch actions.

import { useDispatch } from 'react-redux';

function Product({ id, name, price }) {
const dispatch = useDispatch();

function addToCart() {
dispatch({ type: 'ADD_TO_CART', payload: { id, name, price } });
}

return (
<div>
<h3>{name}</h3>
<p>${price}</p>
<button onClick={addToCart}>Add to Cart</button>
</div>
);
}

In this code, we use the useDispatch hook to get the dispatch function from the store. We define an addToCart function that dispatches the ADD_TO_CART action with the item ID, name, and price as the payload. We then display a button to add the item to the cart.

By using Redux for state management, we can easily manage the state of the cart in our e-commerce application. The cart state is centralized in the store, and all components can access and update it as needed. This makes it easier to manage the state of the application and ensure that it behaves predictably.

Supportive Feature Implementation
One outstanding feature of using Redux for state management is that it allows us to easily add new features to the application. For example, suppose we want to add a feature that allows users to filter the products by category. We can add a new property to the state that represents the selected category, and update the reducer and components accordingly.

const initialState = {
cartItems: [],
selectedCategory: null,
};

function cartReducer(state = initialState, action) {
switch (action.type) {
case 'ADD_TO_CART':
return {
...state,
cartItems: [...state.cartItems, action.payload],
};
case 'REMOVE_FROM_CART':
return {
...state,
cartItems: state.cartItems.filter(item => item.id !== action.payload),
};
case 'SELECT_CATEGORY':
return {
...state,
selectedCategory: action.payload,
};
default:
return state;
}
}

function ProductList() {
const dispatch = useDispatch();
const products = useSelector(state => state.products);
const selectedCategory = useSelector(state => state.selectedCategory);

const filteredProducts = selectedCategory ? products.filter(product => product.category === selectedCategory) : products;

function selectCategory(category) {
dispatch({ type: 'SELECT_CATEGORY', payload: category });
}

return (
<div>
<h2>Products</h2>
<div>
<button onClick={() => selectCategory(null)}>All</button>
<button onClick={() => selectCategory('electronics')}>Electronics</button>
<button onClick={() => selectCategory('clothing')}>Clothing</button>
</div>
<ul>
{filteredProducts.map(product => (
<li key={product.id}>
<Product {...product} />
</li>
))}
</ul>
</div>
);
}In conclusion, Redux is a powerful state management library that can help manage state in a React application. It provides a centralized and predictable way to manage state, making it easier to debug and reason about state changes. Redux follows a strict set of rules for how state changes are made, which makes it easier to debug and understand how the application is behaving. By using Redux, developers can build complex applications with ease and ensure that their code is reusable and maintainable.

In this code, we update the cartReducer function to handle a new action called SELECT_CATEGORY. We also define a new property in the state called selectedCategory that represents the selected category.

In the ProductList component, we use the useSelector hook to access the selectedCategory from the store. We then filter the products based on the selected category and display them in a list. We also provide buttons to select different categories, which dispatch the SELECT_CATEGORY action with the category as the payload.

As you can see, we can easily add new features to our e-commerce application without having to modify a lot of code. The centralized state management system provided by Redux makes it easier to manage the state of the application and ensure that it behaves predictably.

Conclusion

In conclusion, Redux is a powerful state management library that can help manage state in a React application. It provides a centralized and predictable way to manage state, making it easier to debug and reason about state changes. Redux follows a strict set of rules for how state changes are made, which makes it easier to debug and understand how the application is behaving. By using Redux, developers can build complex applications with ease and ensure that their code is reusable and maintainable.

Thank you for reading and Happy Coding!

Build Apps with reusable components, just like Lego

Bit’s open-source tool help 250,000+ devs to build apps with components.

Turn any UI, feature, or page into a reusable component — and share it across your applications. It’s easier to collaborate and build faster.

Learn more

Split apps into components to make app development easier, and enjoy the best experience for the workflows you want:

Micro-Frontends

Design System

Code-Sharing and reuse

Monorepo

Learn more


Redux & State Management Basics was originally published in Bits and Pieces on Medium, where people are continuing the conversation by highlighting and responding to this story.


This content originally appeared on Bits and Pieces - Medium and was authored by Jennifer Roques

Let’s make sharing state easy!

Photo by Ferenc Almasi on Unsplash

Redux is a state management library that is used to manage the state of an application. It provides a predictable and centralized way to manage the state of an application, making it easier to debug and reason about. Redux is not a standalone library; it is often used with React and other libraries to build complex applications. In this article, we will explore Redux and how it can help manage state in a React application.

What is State Management?

In software development, state refers to the condition or status of an application at a particular point in time. State management involves handling and manipulating this state throughout the life cycle of an application. Managing state is crucial for building complex applications because it enables the application to respond to user input and produce the correct output.

In a React application, state management can become challenging as the application grows more complex. Managing state with React’s built-in state management system can become cumbersome, especially when passing state between different components. Redux solves this problem by providing a centralized state management system that can be accessed by all components.

What is Redux?

Redux is a state management library that was inspired by Flux, a pattern for managing state in web applications. Redux is based on three fundamental principles: a single source of truth, state is read-only, and changes are made with pure functions. Let’s explore these principles in more detail.

Single Source of Truth

In a Redux application, there is a single source of truth for the entire application. This source of truth is called the store and is an object that holds the entire state of the application. All components in the application can access this state through the store, and changes to the state can be made through actions.

State is Read-only

The state in a Redux application is read-only, which means that components cannot modify the state directly. Instead, changes to the state are made through actions. An action is an object that describes the change that needs to be made to the state. The store receives this action and updates the state accordingly.

Changes are Made with Pure Functions

Redux follows the principles of functional programming, and all changes to the state are made with pure functions. Pure functions take an input and return an output without affecting anything outside the function. In Redux, these functions are called reducers, and they receive the current state and an action and return the new state.

Benefits of Using Redux for State Management

There are several benefits to using Redux for state management in a React application. These benefits include:

  1. Centralized State Management: Redux provides a centralized state management system that can be accessed by all components. This makes it easier to manage state in large applications.
  2. Predictable State Changes: Redux follows a strict set of rules for how state changes are made, which makes it easier to debug and reason about state changes.
  3. Time Travel Debugging: Redux allows you to track the changes to the state over time, making it easier to debug and understand how the application is behaving.
  4. Reusable Code: Redux code is reusable, which means that it can be used in different applications without having to rewrite the same code.

Let’s look at an example:

Suppose we are building a simple e-commerce website that allows users to add items to their cart and checkout. We want to use Redux to manage the state of the cart.

Step 1: Set up the Redux Store
First, we need to set up the Redux store. We can use the createStore function from the redux library to create the store. We also need to define a reducer function that will handle changes to the cart state.

import { createStore } from 'redux';

const initialState = {
cartItems: [],
};

function cartReducer(state = initialState, action) {
switch (action.type) {
case 'ADD_TO_CART':
return {
...state,
cartItems: [...state.cartItems, action.payload],
};
case 'REMOVE_FROM_CART':
return {
...state,
cartItems: state.cartItems.filter(item => item.id !== action.payload),
};
default:
return state;
}
}

const store = createStore(cartReducer);

In this code, we define an initial state with an empty cart. The cartReducer function handles two actions: ADD_TO_CART and REMOVE_FROM_CART. When the ADD_TO_CART action is dispatched, it adds the item to the cartItems array in the state. When the REMOVE_FROM_CART action is dispatched, it removes the item with the specified ID from the cartItems array.

Step 2: Connect the Component to the Store

import { useSelector } from 'react-redux';

function Cart() {
const cartItems = useSelector(state => state.cartItems);

return (
<div>
<h2>Cart</h2>
<ul>
{cartItems.map(item => (
<li key={item.id}>
{item.name} - ${item.price}
<button onClick={() => dispatch({ type: 'REMOVE_FROM_CART', payload: item.id })}>Remove</button>
</li>
))}
</ul>
</div>
);
}

In this code, we use the useSelector hook to access the cartItems array from the store. We then display the items in a list and provide a button to remove items from the cart. When the button is clicked, we dispatch the REMOVE_FROM_CART action with the item ID as the payload.

Step 3: Dispatch Actions to the Store
Finally, we need to dispatch actions to the store to add or remove items from the cart. We can use the useDispatch hook from the react-redux library to dispatch actions.

import { useDispatch } from 'react-redux';

function Product({ id, name, price }) {
const dispatch = useDispatch();

function addToCart() {
dispatch({ type: 'ADD_TO_CART', payload: { id, name, price } });
}

return (
<div>
<h3>{name}</h3>
<p>${price}</p>
<button onClick={addToCart}>Add to Cart</button>
</div>
);
}

In this code, we use the useDispatch hook to get the dispatch function from the store. We define an addToCart function that dispatches the ADD_TO_CART action with the item ID, name, and price as the payload. We then display a button to add the item to the cart.

By using Redux for state management, we can easily manage the state of the cart in our e-commerce application. The cart state is centralized in the store, and all components can access and update it as needed. This makes it easier to manage the state of the application and ensure that it behaves predictably.

Supportive Feature Implementation
One outstanding feature of using Redux for state management is that it allows us to easily add new features to the application. For example, suppose we want to add a feature that allows users to filter the products by category. We can add a new property to the state that represents the selected category, and update the reducer and components accordingly.

const initialState = {
cartItems: [],
selectedCategory: null,
};

function cartReducer(state = initialState, action) {
switch (action.type) {
case 'ADD_TO_CART':
return {
...state,
cartItems: [...state.cartItems, action.payload],
};
case 'REMOVE_FROM_CART':
return {
...state,
cartItems: state.cartItems.filter(item => item.id !== action.payload),
};
case 'SELECT_CATEGORY':
return {
...state,
selectedCategory: action.payload,
};
default:
return state;
}
}

function ProductList() {
const dispatch = useDispatch();
const products = useSelector(state => state.products);
const selectedCategory = useSelector(state => state.selectedCategory);

const filteredProducts = selectedCategory ? products.filter(product => product.category === selectedCategory) : products;

function selectCategory(category) {
dispatch({ type: 'SELECT_CATEGORY', payload: category });
}

return (
<div>
<h2>Products</h2>
<div>
<button onClick={() => selectCategory(null)}>All</button>
<button onClick={() => selectCategory('electronics')}>Electronics</button>
<button onClick={() => selectCategory('clothing')}>Clothing</button>
</div>
<ul>
{filteredProducts.map(product => (
<li key={product.id}>
<Product {...product} />
</li>
))}
</ul>
</div>
);
}In conclusion, Redux is a powerful state management library that can help manage state in a React application. It provides a centralized and predictable way to manage state, making it easier to debug and reason about state changes. Redux follows a strict set of rules for how state changes are made, which makes it easier to debug and understand how the application is behaving. By using Redux, developers can build complex applications with ease and ensure that their code is reusable and maintainable.

In this code, we update the cartReducer function to handle a new action called SELECT_CATEGORY. We also define a new property in the state called selectedCategory that represents the selected category.

In the ProductList component, we use the useSelector hook to access the selectedCategory from the store. We then filter the products based on the selected category and display them in a list. We also provide buttons to select different categories, which dispatch the SELECT_CATEGORY action with the category as the payload.

As you can see, we can easily add new features to our e-commerce application without having to modify a lot of code. The centralized state management system provided by Redux makes it easier to manage the state of the application and ensure that it behaves predictably.

Conclusion

In conclusion, Redux is a powerful state management library that can help manage state in a React application. It provides a centralized and predictable way to manage state, making it easier to debug and reason about state changes. Redux follows a strict set of rules for how state changes are made, which makes it easier to debug and understand how the application is behaving. By using Redux, developers can build complex applications with ease and ensure that their code is reusable and maintainable.

Thank you for reading and Happy Coding!

Build Apps with reusable components, just like Lego

Bit’s open-source tool help 250,000+ devs to build apps with components.

Turn any UI, feature, or page into a reusable component — and share it across your applications. It’s easier to collaborate and build faster.

Learn more

Split apps into components to make app development easier, and enjoy the best experience for the workflows you want:

Micro-Frontends

Design System

Code-Sharing and reuse

Monorepo

Learn more


Redux & State Management Basics was originally published in Bits and Pieces on Medium, where people are continuing the conversation by highlighting and responding to this story.


This content originally appeared on Bits and Pieces - Medium and was authored by Jennifer Roques


Print Share Comment Cite Upload Translate Updates
APA

Jennifer Roques | Sciencx (2023-03-09T01:51:01+00:00) Redux & State Management Basics. Retrieved from https://www.scien.cx/2023/03/09/redux-state-management-basics/

MLA
" » Redux & State Management Basics." Jennifer Roques | Sciencx - Thursday March 9, 2023, https://www.scien.cx/2023/03/09/redux-state-management-basics/
HARVARD
Jennifer Roques | Sciencx Thursday March 9, 2023 » Redux & State Management Basics., viewed ,<https://www.scien.cx/2023/03/09/redux-state-management-basics/>
VANCOUVER
Jennifer Roques | Sciencx - » Redux & State Management Basics. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2023/03/09/redux-state-management-basics/
CHICAGO
" » Redux & State Management Basics." Jennifer Roques | Sciencx - Accessed . https://www.scien.cx/2023/03/09/redux-state-management-basics/
IEEE
" » Redux & State Management Basics." Jennifer Roques | Sciencx [Online]. Available: https://www.scien.cx/2023/03/09/redux-state-management-basics/. [Accessed: ]
rf:citation
» Redux & State Management Basics | Jennifer Roques | Sciencx | https://www.scien.cx/2023/03/09/redux-state-management-basics/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.