Home >Web Front-end >JS Tutorial >Guide to Redux: A Robust State Management Library for JavaScript Applications
Redux is widely recognized as a robust state management library designed specifically for JavaScript applications, often utilized in tandem with the popular framework React. By offering a dependable state container, Redux establishes a solid foundation that greatly simplifies the task of handling and troubleshooting application states. This guide delves deeply into the fundamental components that comprise Redux, providing detailed explanations of each element and illustrating how they synergistically interoperate to streamline the overall functionality of the application. This in-depth exploration aims to elucidate the inner workings of Redux, empowering developers to grasp the intricacies of this state management tool and harness its capabilities effectively in their projects.
Redux follows a unidirectional data flow model and is based on three core principles:
First, install Redux and React-Redux:
npm install redux react-redux @reduxjs/toolkit
This command installs the core Redux library, the React bindings for Redux, and the Redux Toolkit, which simplifies many common tasks like setting up the store and creating slices.
Actions are payloads of information that send data from your application to your Redux store. Action types are constants that represent the action.
export const INCREMENT = "INCREMENT"; export const DECREMENT = "DECREMENT"; export const INCREMENT_BY_VALUE = "INCREMENT_BY_VALUE"; export const RESET = "RESET"; export const increment = () => ({ type: INCREMENT }); export const decrement = () => ({ type: DECREMENT }); export const incrementByValue = (value) => ({ type: INCREMENT_BY_VALUE, payload: value, }); export const reset = () => ({ type: RESET });
Defining actions and action types clearly helps maintain consistency and reduces errors in your application.
Reducers specify how the application's state changes in response to actions sent to the store. Slices are a collection of Redux reducer logic and actions for a single feature of your app, created using Redux Toolkit's createSlice method.
import { createSlice } from "@reduxjs/toolkit"; const initialState = { number: 0 }; const counterSlice = createSlice({ name: "counter", initialState, reducers: { increment: (state) => { state.number += 5; }, decrement: (state) => { state.number = Math.max(0, state.number - 5); }, incrementByValue: (state, action) => { state.number += action.payload; }, reset: (state) => { state.number = 0; }, }, }); export const { increment, decrement, incrementByValue, reset } = counterSlice.actions; export default counterSlice.reducer;
To combine multiple slices:
import { combineReducers } from "@reduxjs/toolkit"; import counterReducer from "../slices/counterSlice"; const rootReducer = combineReducers({ counter: counterReducer, }); export default rootReducer;
The store is the object that brings actions and reducers together. It holds the application state, allows access to it via getState(), updates it via dispatch(action), and registers listeners via subscribe(listener).
import { configureStore } from "@reduxjs/toolkit"; import rootReducer from "../reducers/rootReducer"; const store = configureStore({ reducer: rootReducer, }); export default store;
To connect React components to the Redux store, use the Provider component from react-redux to pass the store down to your components, and use the useSelector and useDispatch hooks to access and manipulate the state.
import React from "react"; import { Provider } from "react-redux"; import store from "./redux/store/store"; import Counter from "./components/Counter"; import MusCo from "./MusCo redux Guide to Redux: A Robust State Management Library for JavaScript Applications.png"; function App() { return ( <provider store="{store}"> <div classname="container mx-auto mt-24 text-center"> <img src="%7BMusCo%7D" alt="Guide to Redux: A Robust State Management Library for JavaScript Applications" classname="w-40 mx-auto mt-24 rounded-full"> <h1 classname="container m-auto text-2xl font-semibold text-center text-violet-700"> Practice Redux with <span classname="font-extrabold text-violet-900">MusCo</span> </h1> <div classname="relative inline-block mt-8 text-sm"> <counter></counter> <h5 classname="absolute bottom-0 right-0 mb-2 mr-2 font-semibold text-violet-700"> <span classname="italic font-normal">by</span> <span classname="font-semibold text-violet-900">Mus</span>tafa <span classname="font-semibold text-violet-900">Coskuncelebi</span> </h5> </div> </div> </provider> ); } export default App;
import { useDispatch, useSelector } from "react-redux"; import { decrement, increment, incrementByValue, reset, } from "../slices/counterSlice"; import { useState, useEffect } from "react"; function Counter() { const [value, setValue] = useState(""); const dispatch = useDispatch(); const number = useSelector((state) => state.counter.number); useEffect(() => { const showcase = document.querySelector("#showcase"); if (number <h1 classname="mb-3 text-3xl font-bold mt-7 text-violet-700">Counter</h1> <p classname="text-5xl text-violet-900">{number}</p> <div classname="flex mx-8 space-x-5" style="{{" justifycontent:> <button onclick="{()"> dispatch(increment())} className="w-40 h-10 p-2 mt-5 rounded-md outline-1 outline-violet-500 outline text-violet-900" style={{ backgroundColor: "#c2ff72" }}> Increment by 5 </button> <button onclick="{()"> dispatch(decrement())} className="w-40 h-10 p-2 mt-5 rounded-md outline-1 outline-violet-500 outline text-violet-900" style={number Decrement by 5 </button> </div> <div classname="flex mx-8 mt-5 space-x-3 mb-7" style="{{" justifycontent: alignitems:> <div classname="p-5 space-x-5 rounded-md outline outline-1 outline-violet-500"> <input classname="w-40 h-10 pl-2 rounded-md outline outline-1 outline-violet-500 text-violet-900" onchange="{(e)"> { let newValue = e.target.value.trim(); if (newValue === "") { newValue = ""; reset(); } if (/^\d*$/.test(newValue)) { setValue(newValue); } }} value={value} placeholder="Enter Value" /> <button onclick="{()"> { dispatch(incrementByValue(Number(value))); setValue(""); }} className="w-40 h-10 p-2 rounded-md outline-1 outline-violet-500 outline text-violet-900" style={{ backgroundColor: "#c2ff72" }}> Add this Value </button> </div> </div> <button onclick="{()"> { dispatch(reset()); setValue(""); }} className="w-20 h-10 p-2 text-white rounded-md outline-1 outline-violet-500 outline mb-7 bg-violet-900"> Reset </button> <h3 classname="text-violet-400" id="showcase" style="{{" visibility: marginbottom:> Counter cannot be less than 0 </h3> ); } export default Counter;
Redux is a powerful library for managing state in your applications. By understanding actions, reducers, the store, and how to connect everything to your React components, you can create predictable and maintainable applications.
For more information, check out the official Redux documentation:
By following this guide, you should have a solid understanding of Redux and be able to implement it in your own applications.
The above is the detailed content of Guide to Redux: A Robust State Management Library for JavaScript Applications. For more information, please follow other related articles on the PHP Chinese website!