Redux – A predictable state container for JavaScript applications

Redux – A predictable state container for JavaScript applications

2022-10-10 0 1,246
Resource Number 44985 Last Updated 2025-02-24
¥ 0HKD Upgrade VIP
Download Now Matters needing attention
Can't download? Please contact customer service to submit a link error!
Value-added Service: Installation Guide Environment Configuration Secondary Development Template Modification Source Code Installation

Redux is a predictable state container for JavaScript applications.

Redux – A predictable state container for JavaScript applications插图

Redux It helps you write applications that behave consistently, run in different environments (client, server, and native), and are easy to test. Most importantly, it provides a great developer experience, such as real-time code editing combined with a time travel debugger. You can use Redux with React or any other visual library. It’s small (2kB, including dependencies), but there’s a huge plugin ecosystem available.

The Redux Toolkit is our official recommended way to write Redux logic. It revolves around the Redux core and contains packages and features that we feel are critical to building Redux applications. The Redux Toolkit is built on our suggested best practices, simplifying most Redux tasks, preventing common errors, and making writing Redux applications easier.

Core concepts

Imagine that the state of your application is described as a plain object. For example, the state of a todo app might look like this:

{
  todos: [{
    text: 'Eat food',
    completed: true
  }, {
    text: 'Exercise',
    completed: false
  }],
  visibilityFilter: 'SHOW_COMPLETED'
}

This object is like a “model” except without a setter. This is so that different parts of the code can’t change state at will, leading to hard-to-reproduce errors.

To change something in the state, you need to schedule an action. The action is a simple JavaScript object (note that we didn’t introduce any magic?). It describes what happened. Here are some examples:

{ type: 'ADD_TODO', text: 'Go to swimming pool' }
{ type: 'TOGGLE_TODO', index: 1 }
{ type: 'SET_VISIBILITY_FILTER', filter: 'SHOW_ALL' }

Forcing each change to be described as an operation gives us a clear picture of what is happening in our application. If something changes, we know why it changed. Actions are like crumbs of what has already happened. Finally, to tie the states and actions together, we wrote a function called reducer. Again, there’s nothing magical about it – it’s just a function that takes a state and an action as arguments and returns the next state of the app. Writing such a function for a large application would be difficult, so let’s write smaller functions to manage part of the state:

function visibilityFilter(state = 'SHOW_ALL', action) {
  if (action.type === 'SET_VISIBILITY_FILTER') {
    return action.filter
  } else {
    return state
  }
}

function todos(state = [], action) {
  switch (action.type) {
    case 'ADD_TODO':
      return state.concat([{ text: action.text, completed: false }])
    case 'TOGGLE_TODO':
      return state.map((todo, index) =>
        action.index === index
          ? { text: todo.text, completed: !todo.completed }
          : todo
      )
    default:
      return state
  }
}

We wrote another reducer to manage the full state of our application by calling both reducers to get the corresponding state keys:

function todoApp(state = {}, action) {
  return {
    todos: todos(state.todos, action),
    visibilityFilter: visibilityFilter(state.visibilityFilter, action)
  }
}

This is basically the whole idea of Redux. Note that we’re not using any Redux API. It comes with some utilities to facilitate this pattern, but the main idea is that you describe how your state updates over time in response to action objects, and 90% of the code you write is just plain JavaScript, without using Redux itself, its API, or any magic.

Install Redux

The Redux Toolkit includes the Redux core, And other key packages (such as Redux Thunk and Reselect) that we feel are critical for building Redux apps.
This can be used with module bundlers or Node applications as a package on NPM:

# NPM
npm install @reduxjs/toolkit

# Yarn
yarn add @reduxjs/toolkit

It can also be used as a UMD build, This can be loaded from the dist folder of the on unpkg. UMD builds make Redux Toolkit available as window.RTK global variables.

Redux

# NPM
npm install redux

# Yarn
yarn add redux

You’ll also need React bindings and developer tools class=”data-color–tt-darkmode-bec1c7″>.

npm install react-redux
npm install --save-dev @redux-devtools/core

Note that unlike Redux itself, many packages in the Redux ecosystem don’t provide UMD builds, We recommend using Webpack and Browserify CommonJS module bundling for the most comfortable development experience.

Create a React Redux

The recommended way to start a new app with React and Redux is to use official Redux+JS or Redux+TS template Create React App, Redux Toolkit and React Redux integration with React components.

# Redux + Plain JS template
npx create-react-app my-app --template redux

# Redux + TypeScript template
npx create-react-app my-app --template redux-typescript

Configure your store

First, let’s look at index.js where we created the store:

import React from 'react'
import { render } from 'react-dom'
import { Provider } from 'react-redux'
import { createStore } from 'redux'
import rootReducer from './reducers'
import App from './components/App'

const store = createStore(rootReducer)

render(
  <Provider store={store}>
    <App />
  </Provider>,
  document.getElementById('root')
)

In this code, we pass the reducer to the ReduxcreateStore function, The function returns a store object. We then pass this object to the react-redux Provider component, which is rendered at the top of the component tree.

This ensures that whenever we connect to Redux in our application, react-redux connect The store is available to all our components.

Extending Redux

Most apps extend the functionality of their Redux storage by adding middleware or storage enhancers Middleware adds additional dispatch functionality to Redux functions. Enhancers add additional functionality to Redux storage.

We’ll add two middleware and an enhancer:

  • redux-thunk middleware, which allows easy asynchronous use of scheduling.
  • A middleware that records dispatched actions and new states produced.
  • An enhancer that records the time it takes the reducer to process each action.
npm install  redux-thunk

middleware

const logger = store => next => action => {
  console.group(action.type)
  console.info('dispatching', action)
  let result = next(action)
  console.log('next state', store.getState())
  console.groupEnd()
  return result
}

export default logger

enhancer

const round = number => Math.round(number * 100) / 100

const monitorReducerEnhancer =
  createStore => (reducer, initialState, enhancer) => {
    const monitoredReducer = (state, action) => {
      const start = performance.now()
      const newState = reducer(state, action)
      const end = performance.now()
      const diff = round(end - start)

      console.log('reducer process time:', diff)

      return newState
    }

    return createStore(monitoredReducer, initialState, enhancer)
  }

export default monitorReducerEnhancer

Let’s add these to our existing index.js.

    • First, We’ll need importredux-thunk plus our loggerMiddlewareand monitorReducerEnhancer, plus two extra functions that Redux provides: applyMiddlewareand compose.
    • Then we create a store enhancer using applyMiddleware, It takes our loggerMiddleware and applies thunkMiddleware to the store’s dispatch function.

< li > < span class = “data – color – tt – darkmode – bec1c7” > next, we’ll composenewmiddlewareEnhancer and our portfolio monitorReducerEnhancer into a function.

  • This is required because you can only pass one enhancer to createStore. To use multiple enhancers, you must first combine them into one larger enhancer, as shown in this example.
  • Finally, we pass the new composedEnhancers function createStore as its third argument. Note: The second parameter we’ll ignore allows you to preload the state into storage.

 

import React from 'react'
import { render } from 'react-dom'
import { Provider } from 'react-redux'
import { applyMiddleware, createStore, compose } from 'redux'
import thunkMiddleware from 'redux-thunk'
import rootReducer from './reducers'
import loggerMiddleware from './middleware/logger'
import monitorReducerEnhancer from './enhancers/monitorReducer'
import App from './components/App'

const middlewareEnhancer = applyMiddleware(loggerMiddleware, thunkMiddleware)
const composedEnhancers = compose(middlewareEnhancer, monitorReducerEnhancer)

const store = createStore(rootReducer, undefined, composedEnhancers)

render(
  <Provider store={store}>
    <App />
  </Provider>,
  document.getElementById('root')
)

Learning resources

The Redux documentation is designed to teach the basic concepts of Redux and explain key concepts that are used in real-world applications. However, documentation does not cover everything. Happily, there are many other great resources available for learning Redux. We encourage you to check them out. Many of these cover topics that are out of the scope of the documentation or describe the same topics in other ways that might be better suited to your learning style.

Introduction to React, Redux, and Typescript: A set of slides by Redux maintainer Mark Erikson, covering the basics of React, Redux, and TypeScript. Redux topics include store, reducers, middleware, React-Redux, and Redux Toolkit.

https://blog.isquaredsoftware.com/2020/12/presentations-react-redux-ts-intro/

Redux tutorial: Overview and walkthrough: Well written tutorial by Tania Rascia that quickly explains the key concepts of Redux, And shows how to compose a basic Redux + React app using vanilla Redux and the Redux Toolkit.

https://www.taniarascia.com/redux-react-guide/

Redux beginner – a brain-friendly guide to learning Redux: Build a small todo app with the Redux Toolkit and React-Redux, including data fetch-ing.

https://www.freecodecamp.org/news/redux-for-beginners-the-brain-friendly-guide-to-redux/</ p>

Make Redux easy with the Redux Toolkit and Typescript: A helpful tutorial on how to use Redux Toolkit and TypeScript together to write Redux applications, And how RTK simplifies typical Redux usage.

https://www.mattbutton.com/redux-made-easy-with-redux-toolkit-and-typescript/

Basic example

The application’s entire global state is stored in a single storeaction, an object that describes what’s happening, < span>< span class=”data-color–tt-darkmode-b3bbc5″> store. To specify how the state should be updated in response to an action, You write pure reducer function to calculate the new state based on the old state and the operation.

import { createStore } from 'redux'

/**
* This is a reducer - a function that takes the current state value and an action object describing "what happened", and returns a new state value.
* The signature of the reducer is: (state, action) => newState
*
* Redux state should only contain plain JS objects, arrays, and primitives.
* The root state value is usually an object. The important thing is that you shouldn't mutate the state object, but instead return a new object when the state changes.
*
* You can use any conditional logic you want in the reducer. In this example,
* We use a switch statement, but it's not required.
 */
function counterReducer(state = { value: 0 }, action) {
  switch (action.type) {
    case 'counter/incremented':
      return { value: state.value + 1 }
    case 'counter/decremented':
      return { value: state.value - 1 }
    default:
      return state
  }
}

// Create a Redux store to hold your app's state. 
// Its API is {subscribe, dispatch, getState}. 
let store = createStore(counterReducer)

// You can use subscribe() to update the UI in response to state changes. 
// Usually you'd use a view-binding library (like React Redux) instead of subscribing () directly. 
// There may be other use cases that would be helpful for subscriptions as well. 

store.subscribe(() =>  console.log(store.getState()))

// The only way to change internal state is to schedule an action. 
// These actions can be serialized, logged, or stored, and then replayed. 
store.dispatch({ type: 'counter/incremented' })
// {value: 1}
store.dispatch({ type: 'counter/incremented' })
// {value: 2}
store.dispatch({ type: 'counter/decremented' })
// {value: 1}

You don’t need to change the state directly, Instead, you specify the changes to occur using a plain object called actions. Then you write one called reducer to determine how each action transforms the state of the entire application.

Redux toolkit examples

The Redux Toolkit simplifies writing Redux logic and setting up stores. Using the Redux Toolkit, the same logic looks like this:

import { createSlice, configureStore } from '@reduxjs/toolkit'

const counterSlice = createSlice({
  name: 'counter',
  initialState: {
    value: 0
  },
  reducers: {
    incremented: state => {
      //The Redux Toolkit allows us to write "mutation" logic in our reducers. it
      // Without actually mutating the state, because it uses Immer,
      // It detects changes in the "draft state" and generates a brand new one based on those changes
      // Immutable state
      state.value += 1
    },
    decremented: state => {
      state.value -= 1
    }
  }
})

export const { incremented, decremented } = counterSlice.actions

const store = configureStore({
  reducer: counterSlice.reducer
})

// You can still subscribe to the store
store.subscribe(() => console.log(store.getState()))

// Action objects are still passed to 'dispatch', but they are created for us 
store.dispatch(incremented())
// {value: 1}
store.dispatch(incremented())
// {value: 2}
store.dispatch(decremented())
// {value: 1}

The Redux Toolkit allows us to write shorter and easier to read logic, while still following the same Redux behavior and data flow.

—END—

资源下载此资源为免费资源立即下载
Telegram:@John_Software

Disclaimer: This article is published by a third party and represents the views of the author only and has nothing to do with this website. This site does not make any guarantee or commitment to the authenticity, completeness and timeliness of this article and all or part of its content, please readers for reference only, and please verify the relevant content. The publication or republication of articles by this website for the purpose of conveying more information does not mean that it endorses its views or confirms its description, nor does it mean that this website is responsible for its authenticity.

Ictcoder Free Source Code Redux – A predictable state container for JavaScript applications https://ictcoder.com/redux-a-predictable-state-container-for-javascript-applications/

Share free open-source source code

Q&A
  • 1. Automatic: After making an online payment, click the (Download) link to download the source code; 2. Manual: Contact the seller or the official to check if the template is consistent. Then, place an order and make payment online. The seller ships the goods, and both parties inspect and confirm that there are no issues. ICTcoder will then settle the payment for the seller. Note: Please ensure to place your order and make payment through ICTcoder. If you do not place your order and make payment through ICTcoder, and the seller sends fake source code or encounters any issues, ICTcoder will not assist in resolving them, nor can we guarantee your funds!
View details
  • 1. Default transaction cycle for source code: The seller manually ships the goods within 1-3 days. The amount paid by the user will be held in escrow by ICTcoder until 7 days after the transaction is completed and both parties confirm that there are no issues. ICTcoder will then settle with the seller. In case of any disputes, ICTcoder will have staff to assist in handling until the dispute is resolved or a refund is made! If the buyer places an order and makes payment not through ICTcoder, any issues and disputes have nothing to do with ICTcoder, and ICTcoder will not be responsible for any liabilities!
View details
  • 1. ICTcoder will permanently archive the transaction process between both parties and snapshots of the traded goods to ensure the authenticity, validity, and security of the transaction! 2. ICTcoder cannot guarantee services such as "permanent package updates" and "permanent technical support" after the merchant's commitment. Buyers are advised to identify these services on their own. If necessary, they can contact ICTcoder for assistance; 3. When both website demonstration and image demonstration exist in the source code, and the text descriptions of the website and images are inconsistent, the text description of the image shall prevail as the basis for dispute resolution (excluding special statements or agreements); 4. If there is no statement such as "no legal basis for refund" or similar content, any indication on the product that "once sold, no refunds will be supported" or other similar declarations shall be deemed invalid; 5. Before the buyer places an order and makes payment, the transaction details agreed upon by both parties via WhatsApp or email can also serve as the basis for dispute resolution (in case of any inconsistency between the agreement and the description of the conflict, the agreement shall prevail); 6. Since chat records and email records can serve as the basis for dispute resolution, both parties should only communicate with each other through the contact information left on the system when contacting each other, in order to prevent the other party from denying their own commitments. 7. Although the probability of disputes is low, it is essential to retain important information such as chat records, text messages, and email records, in case a dispute arises, so that ICTcoder can intervene quickly.
View details
  • 1. As a third-party intermediary platform, ICTcoder solely protects transaction security and the rights and interests of both buyers and sellers based on the transaction contract (product description, agreed content before the transaction); 2. For online trading projects not on the ICTcoder platform, any consequences are unrelated to this platform; regardless of the reason why the seller requests an offline transaction, please contact the administrator to report.
View details

Related Source code

ICTcoder Customer Service

24-hour online professional services