Introduction
Welcome to our blog, where we will take you on a journey to learn Redux with React.js. Redux is a powerful state management library that works seamlessly with React, enabling efficient data flow and predictable application behavior. In this article, we will break down the process of learning Redux into easy-to-follow sections, providing you with the essential knowledge to build robust React applications with Redux integration. Let's dive in!
we are getting the redux and react-redux from the npm it provides hooks that can connect the redux with react
we are using symmetric UI in the index HTML
Pre-requisite Packages Installation and Setup:
Before diving deeper into Redux, we must ensure that our development environment is set up correctly. We'll guide you through installing and setting up the necessary packages and tools required to integrate Redux seamlessly into your React application.
Redux Installation and Setup:
Once our environment is ready, we'll walk you through the installation and setup of Redux itself. We'll cover the essential Redux packages and configurations needed to initialize and connect the Redux store with our React components.
Understanding Redux Lifecycle Methods:
To grasp the fundamental concepts of Redux, it's crucial to understand its lifecycle methods. We'll explore the core concepts of actions, reducers, and the Redux store, shedding light on how they work together to manage application state effectively.
React/Redux Project Structure:
A well-structured project lays the foundation for maintainable and scalable applications. We'll delve into the recommended folder structure for React/Redux projects, ensuring that your codebase is organized and easy to navigate.
we will see the folder structure for the project
container is for the components,
redux is for file related, redux and it will contain the actions
Creating Redux Action Types:
Actions define the events that trigger state updates in Redux. We'll guide you through the process of creating Redux action types, ensuring consistency and clarity in your application's action system.
in the constant action-type we have created actions like
export const ActionTypes = {
SET_PRODUCTS: "SET_PRODUCTS",
SELECTED_PRODUCT: "SELECTED_PRODUCT",
REMOVE_SELECTED_PRODUCT: "REMOVE_SELECTED_PRODUCT",
};
Creating Redux Actions:
Building upon the previous section, we'll show you how to create Redux actions that encapsulate the changes you want to make to your application's state. You'll learn how to dispatch these actions and trigger state updates accordingly.
Product -actions are
// actions always create the object have key and value,type and payload
import { ActionTypes } from "../contants/action-types";
export const setProduct = (products = {
return: {
type: ActionTypes.SET_PRODUCTS,
payload: products,
},
});
export const selectedProduct = (product = {
return: {
type: ActionTypes.SELECTED_PRODUCT,
payload: product,
},
});
Creating Redux Reducers:
Reducers are responsible for handling actions and updating the application's state accordingly. We'll demonstrate how to create Redux reducers, enabling you to transform actions into meaningful state modifications.
reducer have initial State and actions
here is product reducer
import { ActionTypes } from "../contants/action-types";
const initialState = {
products: [
{
id: 1,
title: "piyush",
category: "programmer and Writer",
},
],
};
export const productReducer = (state = initialState, { type, payload }) => {
switch (type) {
case ActionTypes.SET_PRODUCTS:
return state;
default:
return state;
}
};
and all the reducers will combine in the index.js for more concise code
using the combined reducer
Creating Redux Store:
The Redux store serves as a central repository for your application's state. We'll guide you through the process of creating the Redux store and integrating it with your React application, providing a single source of truth for your data.
we need to store it will take the combined reducer as an argument and then the state like there is no middleware so.
//index..js
import { combineReducers } from "redux";
import { productReducer } from "./productReducer";
const reducers = combineReducers({
allProducts: productReducer,
});
and then the
Adding Redux Dev Tools:
Redux Dev Tools offer invaluable debugging capabilities during development. We'll demonstrate how to integrate Redux Dev Tools into your project, allowing you to inspect and monitor your application's state changes effortlessly.
Store.js
import { createStore } from "redux";
import reducers from "./reducers/index";
const store = createStore(
reducers,
{},
// for the web extension
window._REDUX_DEVTOOLS_EXTENSION_ && window.__REDUX_DEVTOOLS_EXTENSION_()
);
export default store;
Connecting React with Redux:
In this section, we'll explore how to establish a connection between React components and the Redux store. You'll learn how to use the Connect function to access Redux state and dispatch actions, enabling seamless communication between your React components and the Redux store.
connect the react with redux from index.js(src Folder) using provider
Creating React Components:
React components form the building blocks of your application's user interface. We'll cover the process of creating React components that utilize Redux state and dispatch actions, showcasing how to build reusable and efficient UI components.
now jump into the container for the component
for the container file structure will be
Adding Routing to the Project: Routing is a crucial aspect of building multi-page applications. We'll introduce you to a popular routing library and demonstrate how to integrate it into your React/Redux project, enabling navigation between different pages.
Using useSelector to Access State:
React's hooks provide a concise and efficient way to access Redux state. We'll dive into the useSelector hook and showcase how to leverage it to retrieve and utilize the application's state within your React components.
in the product listing
we are using the useSelector which takes the state as an argument
import React from "react";
import { useSelector } from "react-redux";
const ProductListing = () => {
const products = useSelector((state) => state);
console.log(products);
return (
<div className="ui grid container">
<h1>product listing</h1>
</div>
);
};
export default ProductListing;
now the productComponent:
import React from "react";
import { useSelector } from "react-redux";
const ProductComponent = () => {
const products = useSelector((state) => state.allProducts.products);
const { id, title } = products[0];
//console.log(title)
return (
<div className="four column wide">
<div className="ui link cards">
<div className="card">
<div className="image"></div>
<div className="content">
<div className="header">{title}</div>
</div>
</div>
</div>
</div>
);
};
export default ProductComponent;
now use the Shop api for the data and use of Axios for fetching it
we are using the useeffect hook
The useEffect
Hook allows you to perform side effects in your components.
Some examples of side effects are: fetching data, directly updating the DOM, and timers.
useEffect
accepts two arguments. The second argument is optional.
useEffect(<function>, <dependency>)
Using Axios for Redux API Calls:
Integrating API calls with Redux is essential for handling data fetching and updating. We'll explore the popular Axios library and demonstrate how to make API calls within your Redux actions, enabling seamless data integration into your application.
so productlisting.js
import React, { useEffect, useeffect } from "react";
import axios from "axios";
import { useSelector } from "react-redux";
import ProductComponent from "./ProductComponent";
const ProductListing = () => {
const products = useSelector((state) => state);
const fetchProducts = async () => {
const response = await axios
.get("<https://fakestoreapi.com/products>")
.catch((err) => {
console.log("error is ", err);
});
console.log(response);
};
useEffect(() => {
fetchProducts();
}, []);
return (
<div className="ui grid container">
<ProductComponent></ProductComponent>
</div>
);
};
export default ProductListing;
Using useDispatch to Dispatch Actions:
Get The fakeStore API
The useDispatch hook provides an elegant way to dispatch actions within your React components. We'll show you how to utilize this hook to trigger state updates and interact with your Redux store effortlessly.
now we have to dispatch the set product actions with redux hook dispatch
import React, { useEffect, useeffect } from "react";
import axios from "axios";
import { useDispatch, useSelector } from "react-redux";
import ProductComponent from "./ProductComponent";
import { setProduct } from "../redux/actions/productActions";
const ProductListing = () => {
const products = useSelector((state) => state);
const disptach = useDispatch();
const fetchProducts = async () => {
const response = await axios
.get("<https://fakestoreapi.com/products>")
.catch((err) => {
console.log("error is ", err);
});
disptach(setProduct(response.data));
};
useEffect(() => {
fetchProducts();
}, []);
return (
<div className="ui grid container">
<ProductComponent></ProductComponent>
</div>
);
};
export default ProductListing;
here it will dispatch the actions set product and after we pass the all the product set producer will return the object which takes by the reducer which is product Reducer
Updating the Redux Store:
Building upon the previous sections, we'll guide you through the process of updating your Redux store with data fetched from an API call. You'll learn how to modify the application's state in response to asynchronous operations.
so product Reducer is
import { ActionTypes } from "../contants/action-types";
const initialState = {
products: [],
};
export const productReducer = (state = initialState, { type, payload }) => {
switch (type) {
case ActionTypes.SET_PRODUCTS:
return { ...state, products: payload };
default:
return state;
}
};
Rendering Products Listing Page:
To demonstrate the practical implementation of Redux in a real-world scenario, we'll guide you through the process of rendering a products listing page. You'll learn how to retrieve product data from the Redux store and display it in your React components.
product Component
import React from "react";
import { Link } from "react-router-dom";
import { useSelector } from "react-redux";
const ProductComponent = () => {
const products = useSelector((state) => state.allProducts.products);
const renderList = products.map((product) => {
const { id, title, image, price, category } = product;
return (
<div className="four wide column" key={id}>
<Link to={`/product/${id}`}>
<div className="ui link cards">
<div className="card">
<div className="image">
<img src={image} alt={title} />
</div>
<div className="content">
<div className="header">{title}</div>
<div className="meta price">$ {price}</div>
<div className="meta">{category}</div>
</div>
</div>
</div>
</Link>
</div>
);
});
return <>{renderList}</>;
};
export default ProductComponent;
Product Detail Page:
Expanding upon the previous section, we'll explore how to create a product detail page that retrieves detailed information for a selected product. You'll discover how to leverage Redux to manage the state of individual product pages.
now what we have to do is after clicking on it we need to go to a single page of details for that product
detail page
using useparams hook for getting the params as we have to get details from the id of a product
Select and Remove Action Types:
Finally, we'll wrap up our learning journey by discussing how to implement select and remove action types within your Redux-powered application. You'll learn how to enable user interactions such as selecting items and removing them from the Redux store.
after the dispatch and some changes in the action which is in the final commit
product details
import React, { useEffect } from "react";
import axios from "axios";
import { useParams } from "react-router-dom";
import { useDispatch, useSelector } from "react-redux";
import {
selectedProduct,
removeSelectedProduct,
} from "../redux/actions/productActions";
const ProductDetail = () => {
const { productId } = useParams();
let product = useSelector((state) => state.product);
const { image, title, price, category, description } = product;
const dispatch = useDispatch();
const fetchProductDetail = async (id) => {
const response = await axios
.get(`https://fakestoreapi.com/products/${id}`)
.catch((err) => {
console.log("Err: ", err);
});
dispatch(selectedProduct(response.data));
};
useEffect(() => {
if (productId && productId !== "") fetchProductDetail(productId);
return () => {
dispatch(removeSelectedProduct());
};
}, [productId]);
return (
<div className="ui grid container">
{Object.keys(product).length === 0 ? (
<div>...Loading</div>
) : (
<div className="ui placeholder segment">
<div className="ui two column stackable center aligned grid">
<div className="ui vertical divider"></div>
<div className="middle aligned row">
<div className="column lp">
<img className="ui fluid image" src={image} alt={title} />
</div>
<div className="column rp">
<h1>{title}</h1>
<h2>
<a className="ui teal tag label" href="/">
${price}
</a>
</h2>
<h3 className="ui brown block header">{category}</h3>
<p>{description}</p>
<div className="ui vertical animated button" tabIndex="0">
<div className="hidden content">
<i className="shop icon"></i>
</div>
<div className="visible content">Add to Cart</div>
</div>
</div>
</div>
</div>
</div>
)}
</div>
);
};
export default ProductDetail;
thus we have completed the Project🥳🥳🙌
Even if Got some Problem (You are just like me then😅)
recommend course
Fundamentals of Redux Course from Dan Abramov
(Btw Dan Abramov is a software engineer at Meta and a coauthor of the Create React App and Redux)
visit my repository for reference and Full Source code
Conclusion:
Congratulations on completing this comprehensive guide to learning Redux with React.js! And reading this whole blog feel free to post comments and thoughts. We've covered the essential concepts and techniques necessary to build powerful, scalable, and maintainable applications with Redux integration. By leveraging Redux's centralized state management, you can streamline your React projects and create seamless user experiences. Keep practicing and exploring different scenarios to solidify your understanding of Redux, and soon you'll be mastering state management like a pro. Happy coding!
0 Comments