⊗jsrxPmWFRs 12 of 57 menu

Reducers in Redux

In the previous lesson, we used the createSlice function to create a slice for products products and a reducer that will update this slice stored in the store. Let me remind you again that in Redux, state data is changed using reducers.

It is important to remember that there are a number of restrictions imposed on reducers. A reducer updates the state only based on the received values ​​of the current state and the action object, and then decides how to change the state and returns its new value.

We know that by default, objects and arrays in JavaScript are mutable. We also know that you can’t change the state directly, in which case you need to work only with copies. The reducer must also follow this rule. But writing such logic manually can be quite tedious and complex, and here the createSlice function comes to the rescue, which uses the Immer library, which transforms your 'mutable' code in 'immutable'. Thus, you can sin and simplify your life only by using the createSlice or createReducer functions.

The limitations of the reducer also include the use of asynchronous logic, calculating random values, and performing other "side effects". Now that we've gotten to know the reducer better, let's get back to our product app.

Our app has a store that we created in the previous lessons, but it doesn't contain anything yet. Let's open our store.js file and add some code to it. First, let's import the product reducer function:

import productsReducer from '../parts/products/productsSlice'

Now we can specify the imported productsReducer function as a reducer:

export default configureStore({ reducer: { products: productsReducer } })

With the above line we tell our store that now when an action occurs, all data for the slice state.products will be updated by the reducer productsReducer.

Now you can run the application (note that the warning about the invalid reducer has disappeared from the console!), open Redux DevTools in the browser and explore its tabs. For example, by clicking on the State tab in the Inspector tab we can see our two objects with products, which were output as the initial value of the state when the application was first launched. In the Log monitor tab we can see what slices the global state has - this is the products slice, which includes two objects. Also take a look at the Chart tab.

Open your app with your students and change the code in the store.js file as shown in the lesson.

Launch your application in the browser and explore the tabs of the Redux DevTools extension.

enru