Setting up the Redux store

In order to keep things simple initially, and to show how Redux works, we are not going to use connectors for now. We are simply going to replace the state object, and the dispatch function that was previously provided by a Reducer Hook, with Redux.

Let's set up the Redux store now:

  1. Edit src/App.js, and import the useState Hook, as well as the createStore function from the Redux library:
import React, { useState, useEffect, useMemo } from 'react'
import { createStore } from 'redux'
  1. Below the import statements and before the App function definition, we are going to initialize the Redux store. We start by defining the initial state:
const initialState = { todos: [], filter: 'all' }
  1. Next, we are going to use the createStore function in order to define the Redux store, by using the existing appReducer function and passing the initialState object:
const store = createStore(appReducer, initialState)
Please note that in Redux, it is not best practice to initialize the state by passing it to createStore. However, with a Reducer Hook, we need to do it this way. In Redux, we usually initialize state by setting default values in the reducer functions. We are going to learn more about initializing state via Redux reducers later in this chapter.
  1. Now, we can get the dispatch function from the store:
const { dispatch } = store
  1. The next step is removing the following Reducer Hook definition within the App function:
    const [ state, dispatch ] = useReducer(appReducer, { todos: [], filter: 'all' })

It is replaced with a simple State Hook, which is going to store our Redux state:

    const [ state, setState ] = useState(initialState)
  1. Finally, we define an Effect Hook, in order to keep the State Hook in sync with the Redux store state:
    useEffect(() => {
const unsubscribe = store.subscribe(() => setState(store.getState()))
return unsubscribe
}, [])

As we can see, the app still runs in exactly the same way as before. Redux works very similarly to the Reducer Hook, but with more functionality. However, there are slight differences in how actions and reducers should be defined, which we are going to learn about in the following sections.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.141.29.145