Introduction to Redux
This chapter will be mostly focused on looking at and understanding code. The explanations will be limited to the reader, then look at the code themselves and make connections based on what we learned in the previous chapters.
This chapter will look at the Counter app with the Redux template. When we run the default application, we see the following screen:
Following is the file structure of the Redux app highlighting the files we want to look at:
We will first look at the
store.js file to get an idea of the structure of the Redux store:
It has a single slice and is handled by the reducer
counterReducer. Let’s look at the sliced code inside the
The initial state is set to the following:
It has reducers, namely
incrementByAmount. It also has two thunk functions. The first thunk function is the following:
It fetches data from a pseudo-API in the
counterAPI file. It is nothing but a timer that delays sending the data by 500 ms:
The following reducers are handling it:
While it's waiting for the data, the
status key is set to
loading and when it is done, it is set back to
The second thunk function simply dispatches another action based on the current state, conditionally:
There is also a selector being exported from the file:
Now that we know what's in the slice, let’s look at the entry point of the application
We enclose the top-level component into
<Provider> tags and set the
store attribute to the imported store.
The top-level component is from the
The top-level components have the following elements:
In the start, the actions, thunks, and selector has been imported. Along with that, the relevant functions from
The selector has been set to the
count constant in the following lines. You will also notice a local state variable,
incrementAmount. We don’t want to store this variable in the Redux store since we don’t want to make this state value accessible from other components.
In the following section, we use the selector to display the count and use the
dispatch function to dispatch relevant actions on button clicks for decrementing or incrementing the count:
In the next
<div>, we have buttons for incrementing by amount. In this case, we also pass arguments into the dispatch actions, which go into the
payload is a key inside the
action argument, which can be accessed from the reducers.
Why is there a local state variable
incrementAmount in the Counter component?
Select the correct answer