Introduction to Redux | Lecture 257 | React.JS 🔥

The Coding Classroom
19 Feb 202412:14

Summary

TLDRThe video script provides an insightful overview of Redux, a popular third-party library used for managing global state in web applications. Redux can be used with any framework or even vanilla JavaScript, but it is closely associated with React. The script explains Redux's core concept of a single, globally accessible store that is updated via actions, which is similar to the useReducer hook in React. The Redux cycle is described as starting with an action creator in a component, dispatching the action to the store, and then having the appropriate reducer update the state. This leads to a re-render of the UI. The script also touches on Redux's history, its current standing in the development community, and when it is appropriate to use Redux. It concludes by emphasizing Redux's goal of separating state update logic from the rest of the application, making it easier to manage complex state in large applications.

Takeaways

  • 📚 Redux is a third-party library used to manage global state in web applications, and it's not limited to React but can be used with any framework or even Vanilla JavaScript.
  • 🔄 Redux operates on the principle of a single, globally accessible store that holds the application's state, which is updated through actions, similar to the useReducer hook in React.
  • 🤝 Redux is often used in conjunction with React through the react-redux library, which facilitates the connection between the two.
  • 📈 The Redux store can contain one or multiple reducers, each responsible for a specific feature or data domain within the application, ensuring a clear separation of concerns.
  • ⚙️ Action creators in Redux are functions that automate the creation of action objects, centralizing actions and reducing the likelihood of errors.
  • 🔧 Redux is historically significant and was once a staple in React applications for state management, but the landscape has evolved with the introduction of alternative tools.
  • 🚫 Redux is not necessary for every application; it's recommended for use when managing a significant amount of global UI state that requires frequent updates.
  • 📈 Redux Toolkit is a modern approach to writing Redux applications, offering a simpler and more streamlined way to work with Redux compared to classic Redux.
  • 📱 The Context API is sometimes considered a replacement for Redux, but the two serve different purposes and the choice between them depends on the specific needs of the application.
  • 🛠️ Redux is particularly useful for managing non-remote state within an application, while tools like React Query or SWR are better suited for managing remote state.
  • 🏛️ The Redux cycle involves dispatching actions from components to the store, where reducers calculate the new state, leading to a re-render of the UI, encapsulating the state update logic separately from the application.
  • 🏦 Redux can be analogized to a bank system where action creators provide instructions (actions), the dispatcher (store) instructs the vault (state) to update, and the process is managed without direct access to the vault.

Q & A

  • What is Redux and how does it relate to managing global state in a web application?

    -Redux is a third-party library used to manage global state in a web application. It allows for the storage of all global state within a single, globally accessible store, which can then be updated using actions. Redux is not framework-specific and can be used with any framework or even Vanilla JavaScript, but it is commonly associated with React.

  • How is Redux connected with React and what role does react-redux library play in this?

    -Redux has been tightly linked to React, and they can be easily connected using the react-redux library. This library facilitates the integration of Redux with React applications, allowing developers to manage the global state in a structured and predictable manner.

  • What is the significance of actions in Redux and how are they used to update the state?

    -In Redux, actions are used to represent information about how the state should be updated. They are dispatched to the store, which then triggers the appropriate reducer to calculate the next state based on the action type and payload. This process is central to updating the global state in a Redux application.

  • How is the useReducer hook similar to Redux in terms of state management?

    -The useReducer hook in React follows a similar pattern to Redux for state management. It involves creating actions and dispatching them to a reducer function, which calculates the next state. The main difference is that useReducer is used for managing local state within a component, whereas Redux handles global state across the entire application.

  • Why is it recommended to use Redux only when managing a significant amount of global UI state?

    -Redux is recommended for managing a lot of global UI state that needs frequent updates because it provides a centralized store for all global state, making it easier to manage and update. However, for applications with less global state or more remote state, there are often better alternatives available, such as React Query, SWR, or Redux Toolkit Query.

  • What are the two versions of Redux and how do they differ?

    -There are two versions of Redux: classic Redux and the more modern Redux with Redux Toolkit. Classic Redux is the original implementation, while Redux Toolkit is a newer approach that simplifies common Redux patterns and reduces boilerplate code. Both versions are compatible with each other.

  • Why is it important to learn Redux even if it's not used in every React application today?

    -Redux is important to learn for several reasons: it has a reputation for being complex, making it a frequently requested topic; working on a team may involve encountering older code bases that use Redux; and some applications genuinely require a global state management solution like Redux.

  • How does the Redux store function as a centralized container for the application's global state?

    -The Redux store serves as a single source of truth for all global state in an application. It holds the current state tree and allows access to state updates through actions. The store can also contain multiple reducers, each responsible for a different slice of the state, ensuring that the state management remains organized and modular.

  • What is the role of action creators in Redux and how do they simplify the process of creating actions?

    -Action creators in Redux are functions that automatically generate action objects, simplifying the process of creating actions. They centralize action definitions, reducing the likelihood of errors such as typos in action type strings. This approach is optional but is a common practice in building real-world Redux applications.

  • How does the dispatching of actions in Redux relate to the re-rendering of React components?

    -When an action is dispatched to the Redux store, it triggers the reducers to calculate the new state. Once the state is updated, any React components that subscribe to data from the store will re-render to reflect the new state. This ensures that the UI remains in sync with the latest state data.

  • What is the purpose of separating the state update logic from the rest of the application in Redux?

    -Separating the state update logic in Redux allows for a clear distinction between the business logic that manages state transitions and the presentational components that display the UI. This separation makes the application easier to maintain, debug, and reason about, as the state management becomes more predictable and centralized.

  • Can you provide an analogy to explain the flow of updating state with Redux?

    -The process of updating state with Redux can be compared to a bank transaction. The developer acts as the action creator, providing instructions (the action) to the dispatcher, who is like the bank teller. The dispatcher then instructs the store (the bank's vault) to update the state. This analogy emphasizes the indirect nature of state updates in Redux, which must go through a series of defined steps.

Outlines

00:00

📚 Understanding Redux and its Mechanics

This paragraph introduces Redux as a third-party library for managing global state in web applications. It emphasizes Redux's compatibility with various frameworks and its historical association with React. The paragraph explains the Redux pattern of storing global state in a single store and updating it through actions, which is similar to the useReducer hook. It also outlines the importance of understanding the useReducer hook before diving into Redux. The Redux store is compared to a bank vault, where state updates are made through actions, and components re-render in response to these updates. The paragraph concludes with a brief mention of Redux's evolution into two versions: classic Redux and Redux Toolkit, and the importance of learning Redux despite the availability of alternatives.

05:00

🔍 When to Use Redux and Its Mechanics

The second paragraph delves into when it's appropriate to use Redux, suggesting that it should be considered when managing a significant amount of global UI state that requires frequent updates. It differentiates between UI state and remote state, noting that modern alternatives like React Query, SWR, and Redux Toolkit Query are better suited for remote state management. The paragraph explains that Redux might be ideal for non-remote state management but acknowledges that many applications no longer require it. It then reviews the mechanics of Redux, drawing parallels with useReducer, and describes the process of creating actions, dispatching them to the store, and how reducers calculate the next state. The paragraph also touches on the concept of action creators to streamline action creation and maintain consistency across the application.

10:04

🔄 The Redux Cycle and its Simplification

The final paragraph simplifies the Redux process, often referred to as the 'Redux cycle'. It outlines the steps involved in updating global state with Redux: calling an action creator, dispatching the resulting action, the action reaching the store, the appropriate reducer updating the state, and finally, the UI re-rendering. The paragraph uses the analogy of a bank transaction to illustrate the Redux process, with the user as the action creator, the action as the instruction, and the dispatcher as the intermediary between the user and the Redux store, which is likened to a bank vault. The paragraph concludes by assuring readers that the Redux fundamentals will be explained step by step, aiming to make the concept clear by the end of the section.

Mindmap

Keywords

💡Redux

Redux is a third-party library used for managing global state in web applications. It is a standalone library that can be used with any framework or even with Vanilla JavaScript. Redux is often associated with React and is used to maintain a single source of truth for the application's state, which is updated through actions. In the video, Redux is compared with the useReducer hook, and it is mentioned that understanding useReducer is essential for grasping Redux.

💡useReducer hook

The useReducer hook is a React-specific feature that allows managing state within functional components. It operates on a similar principle to Redux, where state is updated by dispatching actions to a reducer function. The useReducer hook is used as a basis for understanding Redux, as both implement a pattern of updating state through actions. The video emphasizes that a good understanding of useReducer is necessary before diving into Redux.

💡Global state

Global state refers to the state that is accessible and can be shared across different components within an application. In the context of the video, Redux is introduced as a tool for managing this global state, which is stored in a single, globally accessible store. The video discusses how Redux allows for the centralization of state management, which is a key concept in the theme of the video.

💡Action

An action in Redux is an object that represents an intention to change the state. It typically contains a 'type' property that indicates the type of action to be performed and may also include a 'payload' with additional data required for the state update. Actions are dispatched to the Redux store, triggering the state update process. In the video, actions are compared to the instructions given to a bank teller when making a transaction.

💡Store

The store in Redux is a central repository that holds the entire state tree of the application. It is the single source of truth for the global state and is where actions are dispatched to update the state. The video explains that the store is where all global state lives and is the place where reducers are also defined, making it a central concept in learning Redux.

💡Reducer

A reducer in Redux is a pure function that takes the current state and an action, and returns the next state based on the action's type and payload. Reducers are responsible for calculating the new state of the application in response to dispatched actions. The video mentions that each reducer should be a pure function and that there may be multiple reducers in a store, each handling a specific feature or data domain.

💡Action Creator

An action creator in Redux is a function that returns an action object. It is used to abstract the creation of action objects, making it easier to manage and maintain the actions in an application. The video points out that using action creators helps to centralize actions and reduces the likelihood of errors due to typos in action type strings.

💡React-Redux

React-Redux is a library that provides bindings between React and Redux, making it easier to connect the two. It allows React components to access the Redux store and dispatch actions to update the state. The video mentions react-redux as the library used to connect Redux with React, highlighting its role in the integration process.

💡Context API

The Context API is a feature in React that enables the sharing of data across components without having to pass props down manually through every level of the component tree. The video discusses the Context API as a potential replacement for Redux, but also notes that the decision to use one over the other is more nuanced and depends on the specific needs of the application.

💡Remote state

Remote state refers to the data that is fetched from a server or an external source and is not part of the local UI state. The video differentiates between UI state and remote state, explaining that while Redux is well-suited for managing non-remote or local state, there are better options like React Query or SWR for managing remote state.

💡Redux Toolkit

Redux Toolkit is a more modern approach to writing Redux applications that simplifies common tasks such as store setup, creating reducers, and writing action creators. The video mentions that there are two versions of Redux—classic Redux and Redux Toolkit—and that both will be covered in the course, starting with classic Redux to build a solid foundation.

Highlights

Redux is a third-party library used to manage global state in web applications.

Redux can be used with any framework or even Vanilla JavaScript, but it's closely linked to React.

The Redux store is a globally accessible place where all the global state is stored and can be updated using actions.

The useReducer hook implements a similar pattern to Redux for updating state by dispatching actions.

Redux and useReducer are so similar that understanding useReducer helps in learning Redux.

When the Redux store is updated, all React components consuming data from the store are re-rendered.

Redux is similar to combining the Context API with the useReducer hook.

Some developers consider the Context API as a replacement for Redux, but the truth is more nuanced.

Redux has two versions: classic Redux and the more modern Redux Toolkit.

Redux was historically used in almost every React app for global state management.

Today, many apps don't need Redux anymore due to the availability of alternatives.

Three reasons Redux is included in the course: its reputation, working with older code bases, and some applications requiring something like Redux.

Use Redux when you have lots of global UI state that needs frequent updates.

UI state refers to state about the UI itself or data that doesn't need to be communicated to an API.

For global remote state, there are better options like React Query, SWR, or Redux Toolkit Query.

Redux might be perfect for managing a lot of non-remote state in your app.

Updating state with useReducer involves creating an action with a type and payload, dispatching the action to a reducer, and the reducer calculating the new state.

In Redux, actions are dispatched to the store, not just the reducer.

The Redux store is a centralized container where all global state lives and where reducers are located.

Reducers in the store should be pure functions calculating the next state based on the action and current state.

Create one reducer per application feature or data domain to keep things separated.

Components consuming the updated state in the store will be re-rendered by React.

Action creators are used in Redux to automate the process of writing actions.

Redux aims to separate state update logic from the rest of the application.

Redux is like a bank system where you give instructions to a dispatcher who updates the store (bank vault).

Transcripts

play00:00

‫As always, let's start by getting

play00:03

‫a good understanding of what Redux actually is

play00:07

‫and how the mechanics of Redux work

play00:11

‫especially when compared with the useReducer hook.

play00:15

‫So in a nutshell, Redux is a third-party library

play00:20

‫that we can use to manage global state in a web application.

play00:25

‫And I say web application,

play00:27

‫because Redux is actually a complete standalone library

play00:32

‫that we could use with any framework

play00:34

‫or even Vanilla JavaScript.

play00:37

‫However, Redux has always been tightly linked to React

play00:41

‫and they are actually quite easy to connect

play00:44

‫using the react-redux library as we will do

play00:48

‫throughout this section.

play00:50

‫Now, the big idea behind Redux is that

play00:53

‫all the global state in your application can be stored

play00:57

‫inside this one globally accessible store

play01:00

‫which we can then update using actions.

play01:04

‫And if this sounds familiar,

play01:06

‫it's because the useReducer hook

play01:08

‫implements a very similar pattern.

play01:11

‫So updating state by dispatching actions.

play01:15

‫Remember and in fact, the mechanism behind Redux

play01:19

‫and useReducer is so similar

play01:22

‫that I will assume that you know how to use useReducer

play01:26

‫and build the teaching of Redux onto the knowledge

play01:30

‫that you already have.

play01:32

‫So again, you should have a pretty good understanding

play01:35

‫of the useReducer hook in order to move on in this section.

play01:40

‫And if you don't

play01:41

‫then please go back to that useReducer section first.

play01:45

‫But anyway, the idea of updating state

play01:49

‫in React and in Redux is always the same.

play01:53

‫So in the case of Redux, as soon as we update the store

play01:57

‫all the React components that consume some data

play02:00

‫from the store will be re-rendered.

play02:04

‫So conceptually, if we think about this

play02:07

‫Redux is actually quite similar

play02:09

‫to combining the Context API with the useReducer hook

play02:13

‫as we have done in the World Wise app.

play02:16

‫And in fact, many developers even say

play02:19

‫that the Context API is a replacement for Redux.

play02:24

‫However, the truth is a bit more nuanced than that

play02:27

‫as we will discuss by the end of the section

play02:30

‫once you have some experience with both of these tools.

play02:35

‫Now Redux has a long history

play02:38

‫and so today, there are basically two versions of Redux.

play02:42

‫So two different ways of writing Redux applications,

play02:46

‫but which are totally compatible with each other.

play02:50

‫So we have the classic Redux and we have the more modern way

play02:54

‫of writing Redux with Redux Toolkit.

play02:58

‫And as you would expect, we will learn both of them

play03:01

‫in this section starting with classic Redux

play03:05

‫so that you get the right foundations.

play03:08

‫Okay, now before we move on to learn how Redux works

play03:13

‫let's quickly check out when we should actually use Redux.

play03:18

‫And let's start with some history.

play03:20

‫So historically, a few years back

play03:24

‫Redux was used in almost every React app out there

play03:28

‫for all global state management needs.

play03:31

‫So you really needed to know Redux.

play03:34

‫It was as if Redux was even part of React.

play03:38

‫Today, however the landscape has changed tremendously,

play03:42

‫because there are now many alternatives

play03:45

‫as we have already talked about

play03:47

‫in the advanced state management lecture

play03:49

‫in a previous section.

play03:52

‫So today, many apps don't actually need Redux anymore

play03:56

‫and also don't use Redux anymore.

play04:00

‫And this means

play04:01

‫that you might not even need to learn Redux right now.

play04:05

‫So why is it included in this course then?

play04:09

‫Well, for three big reasons.

play04:11

‫First, since Redux has a reputation

play04:14

‫for being very hard to learn

play04:17

‫this was probably the most requested topic

play04:20

‫for this course by my current students.

play04:23

‫And I think that this course does teach it pretty well

play04:27

‫in an easy to understand way.

play04:30

‫Second, when you're working on a team

play04:32

‫you will likely work with an older code base

play04:35

‫and then you will definitely encounter Redux.

play04:39

‫Therefore, you need to learn how it works

play04:41

‫even if you don't master it.

play04:44

‫And third, some applications do actually require

play04:48

‫something like Redux.

play04:50

‫And so, let's take a look at when that is

play04:53

‫by bringing back this overview from a previous lecture.

play04:58

‫So my recommendation

play05:00

‫and the recommendation of many experts

play05:02

‫is to use a global state management library like Redux,

play05:07

‫only when you have lots of global UI state

play05:10

‫that you need to update frequently.

play05:12

‫And remember that UI state basically means state

play05:16

‫that is not fetched from a server

play05:19

‫that would be remote state.

play05:21

‫So UI state is simply data about the UI itself

play05:25

‫or data that doesn't need to be communicated

play05:28

‫to an API or so.

play05:31

‫And this distinction is really important,

play05:34

‫because remember for global remote state

play05:37

‫we have many better options nowadays like React Query,

play05:42

‫SWR, or even a tool that is kind of included

play05:46

‫in modern Redux Toolkit, which is Redux Toolkit Query.

play05:51

‫So again, do you need to manage a lot

play05:55

‫of non-remote state in your app,

play05:58

‫then Redux might be perfect for that.

play06:01

‫But the truth is that most global state is actually remote

play06:06

‫which is the reason why so many apps

play06:08

‫don't use Redux anymore.

play06:11

‫But we are actually here to learn Redux

play06:14

‫at least if you still think that it's worthwhile.

play06:18

‫And I personally think that it is.

play06:20

‫And so, let's now quickly look at the mechanics

play06:23

‫of how Redux works.

play06:27

‫So as I said in the very beginning,

play06:30

‫this won't be too hard for you,

play06:32

‫because you already know how useReducer works.

play06:35

‫And so, let's just quickly review that.

play06:39

‫So with useReducer when we want to update state

play06:42

‫from an event handler in a component

play06:45

‫we start by creating an action.

play06:48

‫This action is simply an object that usually contains

play06:51

‫a type and a payload,

play06:53

‫which is information about how the state should be updated.

play06:58

‫We then dispatch that action

play07:00

‫to a so-called reducer function.

play07:03

‫The reducer takes the action type and the payload,

play07:07

‫and together with the current state

play07:09

‫calculates the next state, so the new state value.

play07:14

‫And to finish as the state updates,

play07:17

‫of course, the component

play07:19

‫that originated the state transition will re-render.

play07:23

‫So this mechanism should be familiar to you at this point,

play07:27

‫because now we're gonna add two more things onto this

play07:31

‫in order to learn how Redux works.

play07:35

‫So the first difference

play07:36

‫between useReducer and Redux

play07:39

‫is that in Redux we actually dispatch actions

play07:43

‫not simply to the reducer,

play07:45

‫but to the store that we talked about

play07:47

‫at the beginning.

play07:49

‫So this store is a centralized container

play07:52

‫where all global state lives.

play07:55

‫It's like the single source of truth

play07:57

‫of all global state across the entire application.

play08:02

‫The store is also where one or multiple reducers live.

play08:06

‫And just as a reminder

play08:08

‫each reducer must be a pure function

play08:11

‫that has the single task of calculating the next state

play08:15

‫based on the action that was dispatched to the store

play08:19

‫and the current state that's already in the store as well.

play08:23

‫Now, you might be wondering why there are multiple reducers

play08:27

‫in this store.

play08:29

‫Well, it's because we should create one reducer

play08:32

‫per application feature or per data domain

play08:36

‫in order to keep things separated.

play08:38

‫For example, in a shopping app, you could have one reducer

play08:42

‫for the shopping cart, one for some user data,

play08:46

‫and one for the application color theme, for example.

play08:50

‫Finally, any component that consumes the state

play08:53

‫that has been updated in the store

play08:56

‫will as always get re-rendered by React

play08:59

‫at least if we're assuming

play09:01

‫that reusing Redux together with a React app.

play09:06

‫Okay, so that's the Redux store,

play09:08

‫but now let's focus on the action again.

play09:12

‫So in the real world when we use Redux

play09:15

‫we usually use functions called action creators

play09:19

‫in order to automate the process of writing actions.

play09:23

‫So basically, instead of always writing

play09:26

‫these action objects by hand,

play09:29

‫we create functions that do this automatically.

play09:32

‫This has the advantage to keep all actions

play09:35

‫in one central place

play09:37

‫which reduces bucks,

play09:39

‫because developers don't have to remember

play09:41

‫the exact action type strings.

play09:44

‫Just note that this is optional and not a feature of Redux.

play09:49

‫It's just how we build real world Redux apps.

play09:53

‫Then the rest of the process is of course

play09:56

‫just what I explained before.

play09:58

‫Okay, so let's recap how this Redux cycle works

play10:03

‫as I like to call it.

play10:05

‫So in order to update global state with Redux,

play10:09

‫we start by calling an action creator in a component

play10:12

‫and then dispatch the action that resulted

play10:16

‫from the action creator.

play10:18

‫This action will then reach the store

play10:21

‫where the right reducer will pick it up and update the state

play10:25

‫according to the instructions.

play10:27

‫This then triggers a re-render of the UI

play10:31

‫where the cycle finishes.

play10:33

‫And the big goal of all this is to make the state

play10:37

‫update logic separate from the rest of the application.

play10:41

‫And now just for fun, we can take it back

play10:45

‫to the bank analogy,

play10:46

‫when we first talked about useReducer,

play10:50

‫so remember how we said that when you need to take

play10:53

‫or to place money into a bank account,

play10:56

‫you don't do that yourself directly,

play10:59

‫but instead you go to the person at the desk in the bank

play11:03

‫in order to give them your instructions.

play11:06

‫So you don't update the bank vault yourself.

play11:09

‫And Redux is just like that as well.

play11:13

‫So taking the example of depositing $50

play11:17

‫you would definitely be the action creator

play11:20

‫as you are the one giving the instructions.

play11:24

‫The instructions themselves are the action

play11:27

‫and the person that you're talking to

play11:30

‫is very clearly the dispatcher,

play11:32

‫because he is the one who will instruct the bank vault

play11:36

‫to be updated.

play11:38

‫So the bank's vault is like the Redux store

play11:41

‫that you can touch directly,

play11:43

‫but only through the dispatcher.

play11:46

‫And there you have it, this is how Redux works.

play11:50

‫Do you still think that it's super-hard and super-confusing?

play11:55

‫Well, maybe you do and that's 100% not a problem.

play12:00

‫So I will guide you step by step

play12:02

‫through the Redux fundamentals throughout this section.

play12:06

‫And by the end of it all

play12:07

‫I promise that it will be crystal clear.

Rate This

5.0 / 5 (0 votes)

相关标签
ReduxGlobal StateWeb DevelopmentuseReducerReactState ManagementAction CreatorsCentralized StoreReact ComponentsRedux ToolkitContext APIRemote StateUI StateAction Dispatch
您是否需要英文摘要?