Redux - Complete Tutorial (with Redux Toolkit)
Summary
TLDRIn this comprehensive tutorial, the presenter guides viewers through the essentials of Redux and Redux Toolkit, focusing on the core concepts of the state management library. Starting with an overview of Redux's role in managing global state for React applications, the tutorial delves into the three main components: the store, actions, and reducers. The presenter then demonstrates how to build a simple application using Redux Toolkit, showcasing the ease of creating and connecting state slices, actions, and reducers. The video also covers advanced topics, including asynchronous actions with 'createAsyncThunk' and the use of Redux DevTools for debugging. By the end, viewers are equipped with a solid understanding of Redux and its practical implementation in modern web development.
Takeaways
- 📚 Redux is a state management library for maintaining global state in React applications.
- 🏗️ The three main concepts of Redux are the store, actions, and reducers.
- 🛠️ The store holds the global state and is accessible from any component in the React app.
- 🔄 Actions describe changes to the state and have a type and an optional payload.
- 🎯 Reducers are pure functions that determine how the state should be updated based on actions.
- 📂 Redux Toolkit simplifies the setup and usage of Redux by providing utilities like `createSlice` and `createAsyncThunk`.
- 🔄 Immutability is a core principle in Redux, meaning the state should never be directly mutated but copied and replaced with updates.
- 🔗️ React Redux's `Provider` component is used to connect the Redux store to the React app, making the state accessible to all components.
- 🔑 The `useSelector` and `useDispatch` hooks allow React components to access the state and dispatch actions, respectively.
- 🛠️ Asynchronous actions can be handled with `createAsyncThunk`, which enables fetching data or performing other async tasks within Redux.
- 🐛 The Redux DevTools extension is a valuable tool for debugging and visualizing the state changes and actions in a Redux application.
Q & A
What is Redux and what does it do?
-Redux is a state management library that allows you to manage global state in the context of React applications. It enables state to be accessible from any component, regardless of its position in the component tree, making it easier to handle and update application state across different parts of the app.
What are the three main concepts of Redux?
-The three main concepts of Redux are the store, actions, and reducers. The store holds the global state, actions describe changes to the state, and reducers are functions that perform the state changes based on the action type and payload.
How does Redux ensure immutability of state?
-Redux ensures immutability by not allowing direct mutations to the state. Instead, reducers create a copy of the state, make changes to that copy, and then replace the entire state with the updated copy. This prevents unintended side effects and maintains the integrity of the state across the application.
What is a Redux toolkit and how does it simplify Redux setup?
-Redux toolkit is a collection of utilities and conventions that simplify the setup and usage of Redux. It provides functions like 'configureStore' for creating the store, 'createSlice' for generating reducers and actions, and 'createAsyncThunk' for handling asynchronous actions. These utilities reduce boilerplate code and streamline the process of building Redux applications.
How do you create a Redux store using Redux toolkit?
-To create a Redux store with Redux toolkit, you import 'configureStore' from '@reduxjs/toolkit'. You then use 'configureStore' to create your store, passing in an object with a 'reducer' property. Initially, this can be an empty object, and later you can add your reducers from different slices of state.
What is the purpose of the 'Provider' component in React Redux?
-The 'Provider' component in React Redux is used to make the Redux store available to all components in the application. It is a higher-order component that wraps your application, allowing components to access the store and use hooks like 'useSelector' and 'useDispatch' to interact with the Redux state and dispatch actions.
How do you create a slice of state in Redux using Redux toolkit?
-To create a slice of state in Redux with Redux toolkit, you use the 'createSlice' function. This function takes an object with properties like 'name', 'initialState', and 'reducers'. The 'name' is a string that identifies the slice, 'initialState' is the starting state, and 'reducers' is an object where each key is a reducer function that handles specific actions.
What is an action in Redux and how is it structured?
-An action in Redux is an object that describes a change to the state. It has a 'type' property, which is a string that identifies the action, and may have a 'payload' property, which carries additional data needed for the action. Actions are used to trigger updates to the state by being dispatched to the store.
How do you handle asynchronous actions in Redux with Redux toolkit?
-Asynchronous actions in Redux with Redux toolkit are handled using 'createAsyncThunk'. This function creates an action creator that returns a function, which can be an asynchronous operation like an API call. The async thunk action returns a promise, and you can handle the pending, fulfilled, and rejected states in the reducers to update the state accordingly.
What is the Redux DevTools and how does it help with debugging?
-Redux DevTools is a browser extension that provides a visual interface for monitoring and debugging Redux applications. It allows you to track the state changes, inspect actions, and even jump back and forth in time to see the state at different points. This tool is invaluable for understanding the flow of state updates and diagnosing issues in the application.
How does the order of defining synchronous and asynchronous actions differ in Redux toolkit?
-For synchronous actions in Redux toolkit, you first define the reducer and then create the action using 'createSlice'. However, for asynchronous actions, you define the action creator first using 'createAsyncThunk', and then you handle it in the reducers using 'extraReducers' builder, which allows you to handle the pending, fulfilled, and rejected states.
Outlines
📚 Introduction to Redux and Redux Toolkit
The video begins with an introduction to Redux, emphasizing its role as a state management library for React applications. It explains the concept of a global state that is accessible from any component within the application. The three main concepts of Redux are introduced: the store, actions, and reducers. The video promises to build a simple application using Redux Toolkit to demonstrate how these concepts work together and the ease of using modern Redux.
🛠️ Setting Up the Redux Store and React Integration
This section delves into the setup process of the Redux store using Redux Toolkit. It covers the creation of a store, the importance of the store's structure, and the initial setup of the Redux provider in React. The video also discusses the need for TypeScript types to facilitate easier state access and the use of the 'configureStore' function from Redux Toolkit to establish the store.
🔄 Creating the Counter Slice and Initial State
The video demonstrates how to create a counter slice, which is a specific part of the state responsible for the counter functionality. It explains the definition of the state interface, the creation of the initial state, and the use of 'createSlice' from Redux Toolkit to generate the slice and its associated reducer. The process of exporting the reducer and connecting the slice to the store is also covered.
🎯 Implementing Actions and Reducers for Counter Slice
This part of the video focuses on building actions and reducers for the counter slice. It explains the creation of increment and decrement actions and their corresponding reducers. The video highlights the use of 'createSlice' from Redux Toolkit, which simplifies the process and automatically generates action creators. The importance of immutability in Redux and the correct way to update the state are also discussed.
🔄 Handling Asynchronous Actions with Redux Toolkit
The video introduces asynchronous actions using 'createAsyncThunk' from Redux Toolkit. It demonstrates how to create an asynchronous action for incrementing the counter by a specified amount and how to handle this action in the reducer. The concept of 'pending', 'fulfilled', and 'rejected' states in asynchronous actions is explained, along with the use of 'extraReducers' to handle these states.
🌐 Debugging Redux Applications with Redux DevTools
The final section of the video showcases the use of Redux DevTools for debugging Redux applications. It explains how to install and use the tool to monitor actions, track state changes, and inspect the application's state at different points in time. The video emphasizes the benefits of Redux DevTools in understanding the flow of actions and their impact on the state, making it easier to debug and develop Redux applications.
Mindmap
Keywords
💡Redux
💡Store
💡Actions
💡Reducers
💡Immutability
💡Redux Toolkit
💡Provider
💡Selectors
💡Async Thunk
💡Redux DevTools
Highlights
The introduction of Redux as a state management library for global state in React applications.
Explanation of the three main concepts of Redux: store, actions, and reducers.
The store being a global state accessible from any component in the React application.
Actions being used to tell Redux what to do with the state, with two important properties: type and payload.
Reducers are responsible for making updates to the Redux store based on action types, adhering to the concept of immutability.
Creating a simple application using Redux Toolkit to demonstrate how the different pieces come together.
Explanation of how to create a Redux store using Redux Toolkit and connect it to a React application.
Demonstration of creating a counter slice within Redux, including defining state, initial state, and reducers.
How to use the `createSlice` function from Redux Toolkit to simplify the process of setting up reducers and actions.
Building a counter application and connecting it to Redux, showcasing the use of actions and reducers in a practical example.
Introduction to asynchronous actions using `createAsyncThunk` from Redux Toolkit.
Explanation of how to handle different states in asynchronous actions: pending, fulfilled, and error.
The importance of defining action names for asynchronous functions manually, unlike synchronous actions.
Demonstration of using the Redux DevTools for debugging and visualizing the state changes and action dispatches.
How Redux DevTools allows you to jump back and forth in time to see the application's state at different points.
The convenience of Redux Toolkit in automatically handling action names and providing a cleaner setup for Redux slices.
The comprehensive tutorial covering Redux and Redux Toolkit provides a complete understanding, aiming to eliminate the need for further videos on the topic.
Transcripts
what's up guys there is cin here welcome
to the last Redux with Redux toolkit
tutorial video you're ever going to have
to watch I promise you if you watch this
video and you watch it until the end
you're never going to have to watch
another video on this ever again all
right cool we're now on my computer and
we can begin the first thing that I want
to do is just spend a couple of minutes
not too long just talking about Redux as
a whole and also talking about the three
main concepts of Redux the store actions
and reducers and then we are going to
built a simple application using weux
toolkit so that you get to see how all
of the different Pieces come together
and also how easy it is to work with
modern Redux using Redux toit all right
so let's talk about Redux Redux is
essentially a state management library
that allows you to have Global state in
the context of react what this means is
that you can have state that is
accessible from any component no matter
where they are in the tree this is why
it's called a state management library
and it makes it really really easy to
configure figure and to have Global
state in your react applications so
Redux has three different concepts and
they're all super super important the
first concept is the concept of a store
so I'm just going to write store here
Store the store is essentially state it
is the global state that as I've just
mentioned is going to be accessible
across any component no matter where
they are in your react application the
store you get to Define it in any way
that you want you can put whatever you
want in there it's completely up to you
and the needs of the application and
Redux with Redux tool kit will allow you
to easily set this up and then connect
it to your react application now the
store will usually be made up of
multiple slices multiple slices of the
state each responsible for a certain
domain in the application for example
let's say that we had a counter
application we would have a counter
slice a counter slice of our state which
would hold the pieces of state that are
specifically related to the counter so
for example we could do something like
interface and then
counter State and we can Define whatever
state we want for this counter for
example we could do value and that is
going to be of type number we would have
a slice of our state called the counter
state which would hold the value of our
count which is of type number and then
that would be one part of our redu state
then we could maybe have another piece
of our state for example
interace and then we can do user state
with a capital and that will hold all of
the pieces of State for our user for
example is signed in right is the user
currently signed in is the user
currently sign out now of course I'm
grossly over simplifying this in a real
application you would have a lot more
than this but the point is that your
state your Global store in rux is going
to be made up of multiple slices and
they all come together to form one
Global state that is going to be
accessible in your entire application
then the next Concept in Redux is the
concept of actions so I'm going to come
here and do actions actions are
essentially what you use to tell weux
what it should do to the state in the
case of our counter State here we have a
value which is of type number which
means that we might have an action to
increment the count to make this Value
Plus one and we also might have an
action to decrement the count to make
this value minus one actions and Redux
have two properties that are super super
important so let me just write some code
here to illustrate this this is not like
real code this is pseudo code just to
illustrate you what I mean with this
example I'm going to do const increment
that is going to be equal to an object
which is going to have a type that type
is going to be increment I'm just going
to remove this here and then we also
have payload which is going to be one
this is what an action looks like and
let me just do the same thing for a
decrement so I'm just going to come here
and do
decrement now we have two pseudo actions
remember this is pseudo code this is not
real code they have a type which is
always going to be of type string and
this is required this is essentially the
name of this action right reux is going
to use this type to determine what it
should do to the state if it receives an
action with a type of increment it'll
know that it has to increment the state
by one if it receives an action with a
type of decrement it'll know that it has
to decrement the state by one then we
have this payload here which is the
second property of an action this one is
not required this is optional the
payload is essentially any data that you
want to send to Redux in your action so
that it can perform its job let's say
that instead of increment we had an
action that was increment by amount and
we needed a certain amount to increment
our state by our count buy we would use
this payload to pass the actual value
that we want to increment our state buy
that is going to be the payload of this
action but in this case in the case of
increment we don't actually need a
payload because increment really just
means increment by one so in this
specific case we could just go without
this payload we can just remove it here
in both cases because because you don't
want to increment by anything else other
than one so you don't actually need a
payload but if you had an action for
example increment by
amount right we would then need to have
a specific payload cuz we don't know
what amount we want to increment the
state by so in this case to Redux we
would send a payload in this case of 10
it can be anything you want this payload
doesn't have to be a number it's only a
number because we're working in our
counter State suro example right but you
can literally Define your state and your
actions in any way and you can send
whatever payload you want then we have
the third Concept in rux which is the
concept of reducers reducers essentially
are responsible for taking an action and
then depending on the type of the action
will actually go out and make the update
in the Redux store they will use the
type of the action to know what updates
to do and optionally they will use the
payload to do those specific actions to
make those specific updates to the Redux
store now one very important thing to
know about reducers and also to know
about Redux in general is the fact that
reducers will never directly make an
update to the Redux store we have this
concept of immutability which means that
we're never allowed to directly mutate
the state instead what reducers are
going to do is they're going to take the
state they're going to make a copy of
the state and then make those changes to
that copy of the state which will also
have all the other unchange properties
of the state and then will completely
replace the state as a whole with the
copy that has the changes applied we're
never going to directly mutate the state
Redux does not work if you mutate the
state directly you always have to follow
the concept of immutability make a copy
to the state make the changes to that
copy and then override the entire State
this is very important because this is
how Redux Works cool so now with this we
fully understand Redux we understand the
store actions and reducers and how they
all work together which means that we
have everything that we need to actually
start building our simple application
with Redux toolkit so that you actually
get to see how to implement the store
the actions and the reducers and how to
connect all of it together easily with
Redux toolkit so the first thing that we
need to do is we need to create our
store so I'm going to come here to my
file explorer I'm going to make a new
folder and I'm going to just keep things
very simple I'm going to call this
folder state so we'll do state and
inside of this folder I'm going to
create a new file and this one is going
to be store. TS this file is going to
hold our rux store so what we need to do
to create a store is we need to import
something from Redux toolkit so I'm
going to do import configure actually
let me just strike in
import configure store and we have the
import right here we're going to import
configure store from rxjs toolkit and
that is going to allow us to easily
create our store then we're going to
come here and we're going to do export
const store equals configure store this
is going to take a PR es and then an
object as a parameter and then this
object will only take one key and that
is going to be reducer and for now
because we don't actually have any
reducers we're just going to give this
an empty object but as soon as we create
our different reducers our different
slices of our state as we've seen here
we're going to then come here and
connect them using this store so that
then they will be accessible across our
entire application and finally what we
need to do because we are working in
typescript we're going to need to export
two types that are going to be very very
useful as we work with all of the
different components of Redux and Redux
toolkit in our react application so
already copilot is being very helpful it
knows exactly what I want to export the
first type that I want to export if I
can just do it is going to be the root
state so this is essentially the return
type which is a typescript helper
utility of the type of store.get state
so this configure store gives us a store
variable here which has a get State
function and then we can get the return
type of that function to have as our
root state so then in any react
component as you're going to see
whenever we need to access the state
using a selector we're going to be able
to define the state using this root
State type and then we'll have access in
typescript to all of our state super
easily then right below we're going to
export another type and that is going to
be the app dispatch type which is also
going to be very useful so I'm going to
come here and do export type app
dispatch and then of course copilot
knows exactly what I want this comes
from the type of store. dispatch so we
also have another function on the store
called dispatch and we can get the type
of that function and then export this as
this app dispatch type you're going to
see this is going to come very useful
when we're trying to do asynchronous
actions using our used dispatch hook
cool so now with this we've successfully
created our Redux store the next step
for us to do is to connect this store to
react because react by default cannot
directly talk to Redux we have to use a
provider from react Redux to then
connect our store and our entire Redux
application state to react so what I'm
going to do I'm going to come here in my
main file wherever I'm basically
rendering the entire app and then I'm
going to import a
provider if I can type properly I have a
new keyboard that is why this is a
little bit slower Provider from react
Redux and then also we're going to
import our store that we just created so
I'm going to come here and do import
store and that is going to be from.
State SL store this is exactly the store
that we just created right now this
provider comes directly from react vux
and not from toolkit which is what is
going to allow us to connect our Redux
Store to our react application this
provider works with the Redux context
API which if you're not familiar with it
I do have a whole tutorial video on that
that you can watch to get yourself up to
speed and essentially we are going to
wrap our entire app with this provider
provide our store to the provider which
is then going to allow us to use the
store in any react component so I'm
going to come here make a new line and
then just do provider I'm going to give
it the store here and then write below
the app I'm just going to make another
line and then just close this provider
tag and then save and then actually
remove this because this is unneeded and
this is what we need to now connect
react to Redux so we use this provider
we injected it to store using context
which means that that now this store is
going to be accessible to our entire app
and any component no matter where they
are in the tree it's really really
useful now that we have our provider set
up we can actually go and create our
first slice of state so what we're going
to build in this tutorial video is going
to be a simple counter application so
we're going to need to create our
counter slice so I'm going to come here
in my state folder I'm going to make a
new folder called this counter this is
going to hold our counter slice and then
I'm going to make a new file and call it
counter slice. TS this file is going to
contain everything that we need anything
that is related to our counter slice our
actions our reducers our state they're
all going to go in this file so the
first thing that we need to do because
we are working in typescript we need to
Define our state so what I'm going to do
is do
interface counter State and then we're
going to just give it value and that is
going to be of type number we're not
going to give it anything else because
frankly we don't need anything else in
our state then the next step is we need
to actually create our initial state I'm
going to let copilot here be very
helpful we have initial state which is
going to be a type counter State and
that is going to initialize the value to
zero which means that whenever we're
initializing the state it's always going
to start with the value being zero then
what we need to do is come here and
create our actual slice so I'm going to
do const counter slice and that is going
to be equal to create slice and I'm
going to import this directly from rxjs
toolkit that is going to take a
parenthesis and then it's going to take
an object as a parameter the keys that
we're going to give to this object are
the name that is going to be the name of
our slice which is going to be counter
we don't want to do anything fancy right
this is a simple name for a simple slice
then it's going to take in an initial
state which we can just give it here
initial state that is going to be the
state that this slice will start with
and then we can give it some reducers so
I'm just going to do reducers and then
for now we're not going to have any
actual reducer so this is just going to
be a simple empty object and then we're
going to come here at the bottom and do
something really really cool I'm going
to do export default count C
slice. reducer and then save this
essentially because we're using Create
slice from Redux JS toolkit this gives
us a lot of benefits a lot of cool
things behind the scenes without us
having to set up anything just by
defining this slice here we
automatically get access to a reducer
which we're exporting here by doing
counter slice. reducer this is only
available because we're using crate
slice from rxjs toolkit and it's doing a
lot of the magic for us if we weren't to
use this we would have had to do a lot
more boilerplate code to achieve the
same functionality so now with this
we've efficiently and easily exported
the reducer as the default export of
this file which means that we can now
come here to our store where we defined
our store and we had this empty reducer
key here and we can import that reducer
that we just created so I'm going to
come here and do import counter reducer
from and that's going to be dot counter
SLC counter slice essentially this is
the reducer that we just exported here
as the default export then inside of
this reducer object here instead of it
being empty I'm going to do counter
counter reducer and now we've
essentially connected the counter slice
to our store which is then going to be
accessible using this provider to our
entire react application the beauty of
setting it up this way is that you can
have as many slices as you want as we've
seen before right we had the counter
State here we had the user State we can
have any number of states we would just
create a slice for each of those States
they would have their own individual
slices of state and very soon we're
going to see actions and reducers and
then you can just combine all of them
here which makes it really really easy
to have separation of concerns each
slice is responsible for its own State
and nothing else and it makes everything
really organized and really really easy
to work with cool so now let's actually
build some actions and reducers now
Redux toolkit makes this really really
simple the only thing that we need to do
to create both AED reducer and an action
is just toine a reducer here so I'm
going to make a new line here and what
I'm going to do is I'm just going to do
increment and that is going to be our
reducer and reducers they always take a
state as a parameter and then they will
just return here and let me just see if
copilot can do it yes it can so reducers
you have to Define them by a name you
have to give them a key and then they
will always take a state and optionally
if I can just type properly my keyboard
is really hard to get used to they will
also take here an action but this is
optional this doesn't always need to
happen because it can happen in the case
of increment for example where you don't
actually need to use anything from the
action you just know that you have an
increment and you just need to update
the state to plus one so in this case
specifically for the increment reducer
we're just not going to give this
because this is going to be an unused
property now there's something really
interesting that I want you to pay
attention to because this is super
important remember how in the beginning
of the video I said that Redux you never
mutate the state directly you always
make a copy to the state and then you
replace the entire state with it well
here it seems that this increment
reducer will take the state and then
will directly assign state. Value Plus
equals 1 isn't this directly mutating
the state is this a mistake well no this
isn't a mistake but at the same time I'm
not sure how I feel about this because
this can get really confusing especially
to someone that's just starting out with
Redux essentially what's happening is
because we're using crate slice from
Redux toolkit as I've said this does a
lot of the magic for us behind the
scenes so that we don't have to do it
and essentially What's Happening Here is
this create slice is smart enough to
know that we want to make this update to
the state so it allows us to write
mutating code right which I put in
quotes because we're not actually
mutating it and what it is going to do
is behind the scenes it's going to make
its own copy of the state apply this
change to that copy and then return to
us the value that new state then
overwrite this allows us to write
mutating code which makes it easier for
us because we don't have to make all
those copies and manage those but at the
cost of it being a little bit confusing
because it does look like we're writing
mutating code so just remember because
this is really important you can only do
this if you're using Create slice from
Redux otherwise you cannot do this and
you would have had to make your own copy
of the state and do all of that manually
but because we're using this we don't
have to do it and it's handled
automatically for us which Again mix
feeling LS it's convenient but it's also
confusing great so now that we
understand that we can make our next
reducer which is going to be the decr
case this is going to be very simple
it's going to be exactly the same thing
we're going to do
decrement that is also going to take the
state here and also that is going to do
state. value minus one again because
we're using Create slice we can do this
and it's not going to be a problem we're
not actually going to mutate the state
directly so now these are our reducers
we've just told reux that we have two
reducers increment and decrement and
this is how the state should update
whenever we have actions that actually
want to trigger those reducers so then
how do we create those actions well this
is another point of the magic of Redux
toolkit we can easily get access to the
actions by just doing export con and I'm
going to let copile it be very helpful
we're going to export con increment and
decrement from counter slice. actions so
just like we were able to get access to
the reducer from this counter slice
using rux toolkit we're also able to get
the action directly from this counter
slice and it is smart enough to know
that we only have an increment action
and a decrement action so this makes it
really really easy because we don't have
to write any extra code to create our
actions and now we've exported our
actions which means that we can directly
use them in our react components so we
can then come here to our app we can get
rid of all of this introductionary code
that we had before we can save this and
then we can go to our counter component
which for now is empty so now what we're
going to do is we're going to connect
this counter component to Redux to
access the state and also we're going to
connect it so that it's able to dispatch
some actions so the first thing that we
need to do is we need to connect this to
the state so I'm going to make here a
new line and I'm going to do const count
is going to be equal to use selector
that is going to come from react Redux
this is a function this is a hook so it
takes a parenthesis and then it also
takes a state as a parameter and then it
will return something here so let's just
do state. count this is not correct
correct because we haven't yet added any
types to our state now remember if I go
here to the store we've exported two
different types here one of these types
is the root state so we're actually
going to use this root state to Define
our state here so I'm just going to do
here and then root State import this
from state. store and now it knows that
state. count is not valid because that
is not how we defined our state so I'm
going to come here remove this and then
do state DOT and now it knows that we
have a counter slice and then I can do
dot again and that it knows we have a
value which is going to be of type
number because that is how we defined it
in our counter slice here which means
that now this count variable is of type
number because everything is correctly
typed this is how you connect react to
Redux you have to use your selector and
then you get the state and then you can
select literally anything that you want
we could have selected anything besides
the count but in this case we want the
count so that is how we got the count
then the next thing that we need to do
is we need to connect this to dis patch
so that we're able to to dispatch
actions to our Redux store so I'm going
to do here const dispatch and that is
going to be equal to use dispatch which
is also going to come directly from
Redux we are going to use this dispatch
to dispatch actions because as I've said
react cannot directly talk to Redux we
need to use some of the hooks from react
Redux to allow us to have that
functionality to connect between a react
component and our Redux store then I'm
just going to make some space here
create a new line and then we can
actually build out our component so the
first thing that I want to do is maybe
something like H2 and then put our count
here my God it's extremely difficult to
type with this keyboard I can not for
the life me type count there you go
finally after a th years and then I'm
going to create a new div here with
maybe two buttons a button here to let
me just fix this a button here to
increment and then a button here
to to decrement right currently there's
no functions attached to these and we're
going to change that in just a moment so
button on click that is going to be
equal to here we're going to create a
parenthesis create this and this and now
we are going to
dispatch and dispatch takes in an action
and that is going to be our increment
which again we can import directly from
our counter slice so this is essentially
what we've exported here we've exported
this increment action which we can then
import in our counter example and then
we can dispatch it but because it's a
function we also need to put a
parenthesis here then we're going to do
the same thing here for decrement on
click equals here and then open the
parentheses and then Arrow function
dispatch decrement import this as well
and then call this and we are done this
is how you dispatch actions in Redux you
use this dispatch from use dispatch and
then you use the actions that come from
the actions here of our slice and then
you can easily dispatch them and then
everything else is going to be handled
automatically for you now if we go back
to our application we now see our
counter which is initialized with zero
and then we have a button to increment
and a button to decrement the count if I
press it it's going to increment by one
if I press decrement it's going to
decrement and essentially this works
exactly as we expect we have a full
working counter example implemented in
Redux with Redux tokit great so now that
we've seen how this works let's create
another action this time with an
argument cuz right now our increment and
decrement actions didn't not take any
argument so we're going to come here go
back to our slice and then we're going
to create a new reducer and this one
this time is going to be increment by m
if I can type increment by
amount and this one is going to take the
state but also this time it's going to
take an action because we're going to
need to pass a payload to be able to set
by how much we want the state to be
incremented by so I'm going to make this
equal Arrow function and then let's see
what Copilot it does yes it's smart
enough to figure that it can use the
payload of the action to increment the
state bu and then because we are working
in typescript what I want to do is give
this a type so I'm going to come here
and then do
payload payload action we're going to
import this directly from reux toolkit
and then we're going to give it a type
it's going to be number save this and
then we have increment by amount takes
in the state as with any other reducer
and then takes in an optional action
with an optional payload and that
payload is going to be of type number
which means that we can do state. Value
Plus equals action. payload this payload
you could Define it in any way that you
want instead of number we could have had
something like an object here that had
value and then we could do number and
then this would no longer work because
we would have to do actually value to
then get the actual number so it's
number plus number right but we're not
going to do that we're just going to
have count because we want to keep the
symbol and really all we need is a count
but again you can find this in any way
that you want that's the whole point of
Redux is that it depends on the
application and what it needs and you're
free to configure this in any way that
you want and then to get access to this
action all that we have to do is come
here and do increment by amount and
again it already knows that this is an
action so we can easily just use it in
our counter component we can come here
do increment by amount it already knows
and then instead of increment we can do
buy amount and then we can pass it here
10 for example save this go back to
application
increment it's going to increment by 10
increment Again by 10 Again increment
again when I press decrement this one is
still doing it by one so this
application works exactly as you expect
this is how easy it is to create any
number of actions you just Define the
reducer you export the action and
everything just works easily now let me
show you something cool and really
useful we're going to take a look at an
asynchronous action because the reality
is if you're working with three dogs
often times you're going to have to do a
synchronous action for example you want
to fetch some data from an API that has
to be asynchronous and there's a little
bit more differences when you're doing
that versus a simple action that is
synchronous so let's come here and we'll
Define our asynchronous action we're
going to do export const increment
async that is going to be equal to
something new that is going to be equal
to
create async thunk this is also going to
come from meix toolkit this is a paren
es and then it takes a bit of arguments
so the first argument is going to be the
name of the action so we're just going
to do counter SL
increment
async can I type
increment
async a sync and that is going to be a
comma and then it's going to take the
actual function and hopefully we can let
copilot do the work great this is going
to be an asynchronous function it's
going to take in our case a a parameter
that is going to be amount that is going
to be of type number it is going to then
wait for 1 second which is going to
simulate waiting for something to happen
this can simulate for example fetching
data from an API which may very well
take a second and then it's going to
return the amount it's simple it's a
simple example while we're mocking an
asynchronous function but essentially
we're just returning a value here which
is going to then be the payload of this
action now there's two very important
things that we just did here the first
one is the name we haven't actually
defined any name for any of these other
actions here in the reducers that is
because reux toolkit will automatically
do that for us so essentially every
single one of these this is going to be
counter SL increment counter SL
decrement counter SL increment by amount
we're going to see this in just a moment
as we look at the Redux def tools but in
the case of asynchronous functions we
actually had to Define our name
ourselves so we did counter SL increment
async this is the first thing and the
second thing is in the case of a
synchronous actions you always Define
the action first using Create async
thunk and then you define the reducers
when we had synchronous actions we did
the reducers first and then we did the
actions it's a little bit different just
because we're working with asynchronous
functions and also the way that you
define a reducer for an asynchronous
function is different because it doesn't
go in this reducers object it actually
goes here at the bottom in something
that we call extra reducers and this one
will take a function what happened my
keyboard is Playing Tricks on Me again
oh my God this is embarrassing this
whole video should be just darus against
computer against the keyboard this is
going to take a builder as an argument
you don't need to worry about this
Builder is it's just a tool that is
going to allow you to essentially add
cases to these reducers and then again
let's let co-pilot do its thing great we
have builder. ADD case and then here's
the magic we have increment async do
fulfilled we're getting access to do
fulfilled because we used create assing
thunk we're also going to get access is
the pending and then the error State
because when you're working with
asynchronous functions you're always
going to have different states you're
going to have the pending State while
that action is running in the case of
here while we're waiting for this
promise this is going to be in the
pending State the promise hasn't yet
resolved yet in the case of an API fetch
it's the duration that we need to wait
for the data to come back from the API
and then we have the fulfilled State
whenever this promise resolves and we
actually get some data back in this case
the amount we're going to be in this
fulfilled State and as essentially what
we've done is we've told this Builder
this extra reducers Builder to add a
case for the increment async do
fulfilled that should run some code
again it's going to take the state and
an action which is optional and then
it's going to make the same updates to
the state in the same way that we did
them here just slightly different
because we're using this extra reducers
this in concept literally Works in
exactly the same way there's only a
little bit of syntax difference just
because we're working with asynchronous
functions again I'm going to Define here
action I'm going to do action and then
do a colon and then do payload action
and that is going to be of type number
as well just so that we know that this
payload is a type number so that we can
actually add it to the state value and
then this works because we pass a number
here this returns a number everything is
Works no types script is going to
complain then what we're going to do is
we're just going to add another case for
the pending State just so that you get
to see how it works this is not actually
needed for this action because really we
have no use for a pending State however
it's really important they understand
how this concept Works how asynchronous
function work within Redux so we're
going to do this what I'm going to do is
I'm going to come here and do Builder do
add case and that hopefully let's see
can co-pilot yes co-pilot knows exactly
what we want it is really great let's
make a new line here exactly I'm going
to remove this comment because we don't
need this and then what I'm going to do
I'm going to close this parenthesis here
I'm going to remove this Builder here
and I'm just going to chain these ad
cases and save essentially you have one
one Builder you can add one case to it
and then you can chain another case and
you can essentially do this forever and
you can chain as many cases as you want
so now we have a case for the increment
acing pending which again we get access
to because we're using this great acing
thunk otherwise we will not have access
to them and in this one we actually
don't even need a state because we're
not going to actually do anything to the
state so I'm just going to remove this
all we're going to do is we're just
going to console log increment as sing.
pending so that we can see how all of
this works so now with this because
we've already exported this increment
asnc function we can just come here to
our counter we can just do import
increment async and then instead of this
here we can just do increment async and
then we can pass it a number it's
actually going to give us an error
argument of type async thunk this is not
configurable to any action correct we
forgot to do one thing remember here we
had our root State let me just go to its
definition we also have ADD dispatch
which we haven't used that is because we
need to put it here so we're going to do
it app dispatch and for this as well
save this and now we no longer have an
error this is needed if you're working
with asynchronous actions so we've
dispatched the increment async action
again we've passed it this argument
which it knows to expect an argument
because we've defined it here we said
amount is number right so this is the
argument that is going to be used and
then this argument gets return here as
the amount which is then going to come
in this action here as the payload which
is going to allow us to make the state
update to our state so if I save all of
this go back to my counter save all of
this and then if we go back to
application if we also open up the
console here just so that we can see
what's going on if I press increment we
get increment Asing not pending and then
exactly 1 second later our state is
incremented by 10 let's do it again
increment we get the console log and
then a second later we get incremented
by 10 a third time just to be sure
increment console log a second later we
get 30 our application our reux
application now fully supports
asynchronous actions which means that we
can do anything that is asynchronous
here we have a simple increment Asing
but you can do a fetch an API request
you can do anything that you want you
can have any amount of arguments here
you can Define them how you want do
whatever you want in this function
return a payload and then you get access
to this payload here in this reducer
Builder and then you can make any State
updates that you want super super easily
great let me now just show you one last
thing this is going to be super short
but it's going to be worth it and then I
promise you you're never going to have
to watch another video on this ever
again what I want to show you is the
Redux de tools these are really really
useful if you're working with redog
because it helps you debug a lot of
things super easily you can get this for
Chrome it's super easy just Google Redux
def tools and you're going to get it
it's the first link essentially this
will automatically connect to your Redux
store and then tell you everything that
is going on in your application so let
me just refresh here so that we have a
clean slate essentially if I press
increment here let's see what happens we
get counter SL increment asyn SL pending
and then we get counter SL increment
async SL fulfiled these come directly
from our reducers here from our actions
because we use create async thunk
remember we get access to pending and
then fulfilled these are a same match
and remember how I said that we needed
to define the name of this asynchronous
function we had to give it here counter
increment async well that's exactly what
we're seeing here we're seeing counter
SL increment async SL pending this
pending and fulfilled comes directly
from create assing thunk not only that
but here on the right if I select your
fulfilled you get to see exactly the
difference that our state went when this
action was done we went from 0o to 10 if
I press increment again we get a new
pending and this one states are equal
there's no difference because remember
in this one all that we did is we just
did a console log so there's no actual
state upat is being done but in the case
of fulfilled we went from 10 to 20 you
can easily track how all of your updates
happen and which actions caus them if we
then do decrement you're going to see
that the only thing that we have is
counter SL decrement now we never
actually directly set the name of this
action anywhere this is because we use
create slice and then we use these
reducers here and then we exported them
using this using counter slice. actions
this is automatically handled for us so
you never even have to worry about
defining the name of your specific
actions reux toolkit is going to do that
automatically for you and if I click
here you're going to see that our state
went from 20 to 19 this is really useful
because it helps you debug it helps you
figure out what went wrong if something
went wrong in your react application and
you can easily track which which actions
led to which state differences not only
that but another really cool feature of
these def tools is that you can directly
jump to a previous action for example
increment acing fulfilled I can press
jump here and our state now goes back to
the state where this action was done
right you can see here the state we went
from 0 to 10 10 I directly jumped back
in time super easily to see how my
application look like at that specific
point in time I can click back here and
I can jump to the present moment and our
state now is 19 with all of these
different updates you can jump to any
action you can go back in time and
forward in time super easily which makes
it really really easy to debug if you're
working with Redux with toolkit or not
this is really invaluable and I would
always recommend that you install this
because it's really really useful all
right guys that was a really long
tutorial I really hope that you've
enjoyed this that was rux with reux JS
toolkit I promised you in the beginning
of this video that if you watch this
video and you watched it until the end
you wouldn't have to watch another video
on this ever again and I really hope
that I was able to deliver on that
promise if you enjoyed this video and
you want to see more videos like these
you can click here to subscribe it would
really help me out a lot you can also
click here to watch a different video of
mine which I'm sure that it's super
super awesome and with that being said
my name has been darus causin this is
causin Solutions thank you so much for
watching and I will see you all in the
next video cha cha
Ver Más Videos Relacionados
Learn Redux Toolkit in under 1 hour
React & Redux Toolkit - Bases y proyecto práctico
Introduction to Redux | Lecture 257 | React.JS 🔥
Vuex State Management Introduction & Create Store | #35 | Vuex State Management Vue js 3 in Hindi
IBM ReactJs Interview - Fresher | 🎉 Selected | ReactJs & Javascript #reactinterviewquestions #ibm
Why Everyone Loves Zustand
5.0 / 5 (0 votes)